1 const char cgi_rcs[] = "$Id: cgi.c,v 1.70.2.8 2003/04/29 13:33:51 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.8 2003/04/29 13:33:51 oes
42 * Killed a compiler warning on OSX
44 * Revision 1.70.2.7 2003/04/03 13:50:58 oes
45 * - Don't call cgi_error_disabled ifndef FEATURE_CGI_EDIT_ACTIONS
47 * - Show toggle info only if we have it
49 * Revision 1.70.2.6 2003/03/12 01:26:25 david__schmidt
50 * Move declaration of struct tm dummy outside of a control block so it is
51 * accessible later on during snprintf in get_http_time.
53 * Revision 1.70.2.5 2003/03/11 11:53:58 oes
54 * Cosmetic: Renamed cryptic variable
56 * Revision 1.70.2.4 2003/03/07 03:41:03 david__schmidt
57 * 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.
59 * Revision 1.70.2.3 2002/11/28 18:14:32 oes
60 * Disable access to critical CGIs via untrusted referrers.
61 * This prevents users from being tricked by malicious websites
62 * into making unintentional configuration changes:
64 * - Added flag to each cgi_dispatcher that allows or denies
66 * - Introduced proviorical function that greps for the
67 * referrer header before regular header parsing happens
68 * - Added safety check to dispatch_known_cgi. CGI is called
69 * if (cgi harmless || no referrer || we are referrer).
70 * Else a) toggle calls are modified not to change status and
71 * b) all other calls are denied.
73 * Revision 1.70.2.2 2002/11/12 16:20:37 oes
74 * Added missing #ifdef FEATURE_TOGGLE around g_bToggleIJB; fixes bug #636651
76 * Revision 1.70.2.1 2002/08/05 11:17:46 oes
77 * Fixed Bug #587820, i.e. added workaround for IE bug that includes fragment identifier in (cgi) query
79 * Revision 1.70 2002/05/19 11:33:20 jongfoster
80 * If a CGI error was not handled, and propogated back to
81 * dispatch_known_cgi(), then it was assumed to be "out of memory".
82 * This gave a very misleading error message.
84 * Now other errors will cause a simple message giving the error
85 * number and asking the user to report a bug.
88 * http://sourceforge.net/tracker/index.php?func=detail
89 * &aid=557905&group_id=11118&atid=111118
91 * Revision 1.69 2002/05/14 21:28:40 oes
92 * - Fixed add_help_link to link to the (now split) actions
93 * part of the config chapter
94 * - Renamed helplink export to actions-help-prefix
96 * Revision 1.68 2002/05/12 21:36:29 jongfoster
97 * Correcting function comments
99 * Revision 1.67 2002/04/30 12:02:07 oes
100 * Nit: updated a comment
102 * Revision 1.66 2002/04/26 18:32:57 jongfoster
103 * Fixing a memory leak on error
105 * Revision 1.65 2002/04/26 12:53:51 oes
106 * - New function add_help_link
107 * - default_exports now exports links to the user manual
108 * and a prefix for links into the config chapter
110 * Revision 1.64 2002/04/24 02:17:21 oes
111 * - Better descriptions for CGIs
112 * - Hide edit-actions, more shortcuts
113 * - Moved get_char_param, get_string_param and get_number_param here
116 * Revision 1.63 2002/04/15 19:06:43 jongfoster
119 * Revision 1.62 2002/04/10 19:59:46 jongfoster
120 * Fixes to #include in templates:
121 * - Didn't close main file if loading an included template fails.
122 * - I'm paranoid and want to disallow "#include /etc/passwd".
124 * Revision 1.61 2002/04/10 13:37:48 oes
125 * Made templates modular: template_load now recursive with max depth 1
127 * Revision 1.60 2002/04/08 20:50:25 swa
130 * Revision 1.59 2002/04/05 15:51:51 oes
131 * - added send-stylesheet CGI
132 * - bugfix: error-pages now get correct request protocol
134 * - kludged CGI descriptions and menu not to break JS syntax
136 * Revision 1.58 2002/03/29 03:33:13 david__schmidt
137 * Fix Mac OSX compiler warnings
139 * Revision 1.57 2002/03/26 22:29:54 swa
140 * we have a new homepage!
142 * Revision 1.56 2002/03/24 17:50:46 jongfoster
143 * Fixing compile error if actions file editor disabled
145 * Revision 1.55 2002/03/24 16:55:06 oes
146 * Making GIF checkerboard transparent
148 * Revision 1.54 2002/03/24 16:18:15 jongfoster
151 * Revision 1.53 2002/03/24 16:06:00 oes
152 * Correct transparency for checkerboard PNG. Thanks, Magnus!
154 * Revision 1.52 2002/03/24 15:23:33 jongfoster
157 * Revision 1.51 2002/03/24 13:25:43 swa
158 * name change related issues
160 * Revision 1.50 2002/03/16 23:54:06 jongfoster
161 * Adding graceful termination feature, to help look for memory leaks.
162 * If you enable this (which, by design, has to be done by hand
163 * editing config.h) and then go to http://i.j.b/die, then the program
164 * will exit cleanly after the *next* request. It should free all the
165 * memory that was used.
167 * Revision 1.49 2002/03/13 00:27:04 jongfoster
170 * Revision 1.48 2002/03/08 17:47:07 jongfoster
173 * Revision 1.47 2002/03/08 16:41:33 oes
174 * Added GIF images again
176 * Revision 1.46 2002/03/07 03:48:38 oes
177 * - Changed built-in images from GIF to PNG
178 * (with regard to Unisys patent issue)
179 * - Added a 4x4 pattern PNG which is less intrusive
180 * than the logo but also clearly marks the deleted banners
182 * Revision 1.45 2002/03/06 22:54:35 jongfoster
183 * Automated function-comment nitpicking.
185 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
186 * - Better error reporting on OS/2
187 * - Fix double-slash comment (oops)
189 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
190 * - Re-enable OS/2 building after new parms were added
191 * - Fix false out of memory report when resolving CGI templates when no IP
192 * address is available of failed attempt (a la no such domain)
194 * Revision 1.42 2002/01/21 00:33:20 jongfoster
195 * Replacing strsav() with the safer string_append() or string_join().
196 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
197 * Adding missing html_encode() to error message generators.
198 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
200 * Revision 1.41 2002/01/17 20:56:22 jongfoster
201 * Replacing hard references to the URL of the config interface
202 * with #defines from project.h
204 * Revision 1.40 2002/01/09 14:26:46 oes
205 * Added support for thread-safe gmtime_r call.
207 * Revision 1.39 2001/11/16 00:48:13 jongfoster
208 * Fixing a compiler warning
210 * Revision 1.38 2001/11/13 00:31:21 jongfoster
211 * - Adding new CGIs for use by non-JavaScript browsers:
212 * edit-actions-url-form
213 * edit-actions-add-url-form
214 * edit-actions-remove-url-form
215 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
218 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
219 * Show enablement/disablement status in almost all templates.
220 * There is a little trickiness here: apparent recursive resolution of
221 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
222 * the actual enablement status. So a similar construct,
223 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
226 * Revision 1.36 2001/10/26 17:33:27 oes
229 * Revision 1.35 2001/10/23 21:48:19 jongfoster
230 * Cleaning up error handling in CGI functions - they now send back
231 * a HTML error page and should never cause a FATAL error. (Fixes one
232 * potential source of "denial of service" attacks).
234 * CGI actions file editor that works and is actually useful.
236 * Ability to toggle Junkbuster remotely using a CGI call.
238 * You can turn off both the above features in the main configuration
239 * file, e.g. if you are running a multi-user proxy.
241 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
242 * Only show "Local support" on templates conditionally:
243 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
244 * - if not, no Local support section appears
246 * Revision 1.33 2001/10/14 22:28:41 jongfoster
247 * Fixing stupid typo.
249 * Revision 1.32 2001/10/14 22:20:18 jongfoster
250 * - Changes to CGI dispatching method to match CGI names exactly,
251 * rather than doing a prefix match.
252 * - No longer need to count the length of the CGI handler names by hand.
253 * - Adding new handler for 404 error when disptching a CGI, if none of
254 * the handlers match.
255 * - Adding new handlers for CGI actionsfile editor.
257 * Revision 1.31 2001/10/10 10:56:39 oes
258 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
260 * Revision 1.30 2001/10/02 15:30:57 oes
261 * Introduced show-request cgi
263 * Revision 1.29 2001/09/20 15:47:44 steudten
265 * Fix BUG: Modify int size to size_t size in fill_template()
266 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
268 * Revision 1.28 2001/09/19 18:00:37 oes
269 * - Deletef time() FIXME (Can't fail under Linux either, if
270 * the argument is guaranteed to be in out address space,
273 * - Pointer notation cosmetics
274 * - Fixed a minor bug in template_fill(): Failiure of
275 * pcrs_execute() now secure.
277 * Revision 1.27 2001/09/16 17:08:54 jongfoster
278 * Moving simple CGI functions from cgi.c to new file cgisimple.c
280 * Revision 1.26 2001/09/16 15:47:37 jongfoster
281 * First version of CGI-based edit interface. This is very much a
282 * work-in-progress, and you can't actually use it to edit anything
283 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
284 * to have any effect.
286 * Revision 1.25 2001/09/16 15:02:35 jongfoster
287 * Adding i.j.b/robots.txt.
288 * Inlining add_stats() since it's only ever called from one place.
290 * Revision 1.24 2001/09/16 11:38:01 jongfoster
291 * Splitting fill_template() into 2 functions:
292 * template_load() loads the file
293 * template_fill() performs the PCRS regexps.
294 * This is because the CGI edit interface has a "table row"
295 * template which is used many times in the page - this
296 * change means it's only loaded from disk once.
298 * Revision 1.23 2001/09/16 11:16:05 jongfoster
299 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
301 * Revision 1.22 2001/09/16 11:00:10 jongfoster
302 * New function alloc_http_response, for symmetry with free_http_response
304 * Revision 1.21 2001/09/13 23:53:03 jongfoster
305 * Support for both static and dynamically generated CGI pages.
306 * Correctly setting Last-Modified: and Expires: HTTP headers.
308 * Revision 1.20 2001/09/13 23:40:36 jongfoster
309 * (Cosmetic only) Indentation correction
311 * Revision 1.19 2001/09/13 23:31:25 jongfoster
312 * Moving image data to cgi.c rather than cgi.h.
314 * Revision 1.18 2001/08/05 16:06:20 jongfoster
315 * Modifiying "struct map" so that there are now separate header and
316 * "map_entry" structures. This means that functions which modify a
317 * map no longer need to return a pointer to the modified map.
318 * Also, it no longer reverses the order of the entries (which may be
319 * important with some advanced template substitutions).
321 * Revision 1.17 2001/08/05 15:57:38 oes
322 * Adapted finish_http_response to new list_to_text
324 * Revision 1.16 2001/08/01 21:33:18 jongfoster
325 * Changes to fill_template() that reduce memory usage without having
326 * an impact on performance. I also renamed some variables so as not
327 * to clash with the C++ keywords "new" and "template".
329 * Revision 1.15 2001/08/01 21:19:22 jongfoster
330 * Moving file version information to a separate CGI page.
332 * Revision 1.14 2001/08/01 00:19:03 jongfoster
333 * New function: map_conditional() for an if-then-else syntax.
334 * Changing to use new version of show_defines()
336 * Revision 1.13 2001/07/30 22:08:36 jongfoster
337 * Tidying up #defines:
338 * - All feature #defines are now of the form FEATURE_xxx
339 * - Permanently turned off WIN_GUI_EDIT
340 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
342 * Revision 1.12 2001/07/29 18:47:05 jongfoster
343 * Adding missing #include "loadcfg.h"
345 * Revision 1.11 2001/07/18 17:24:37 oes
346 * Changed to conform to new pcrs interface
348 * Revision 1.10 2001/07/13 13:53:13 oes
349 * Removed all #ifdef PCRS and related code
351 * Revision 1.9 2001/06/29 21:45:41 oes
352 * Indentation, CRLF->LF, Tab-> Space
354 * Revision 1.8 2001/06/29 13:21:46 oes
355 * - Cosmetics: renamed and reordered functions, variables,
356 * texts, improved comments etc
358 * - Removed ij_untrusted_url() The relevant
359 * info is now part of the "untrusted" page,
360 * which is generated by filters.c:trust_url()
362 * - Generators of content now call finish_http_response()
363 * themselves, making jcc.c:chat() a little less
366 * - Removed obsolete "Pragma: no-cache" from our headers
368 * - http_responses now know their head length
370 * - fill_template now uses the new interface to pcrs, so that
371 * - long jobs (like whole files) no longer have to be assembled
372 * in a fixed size buffer
373 * - the new T (trivial) option is used, and the replacement may
374 * contain Perl syntax backrefs without confusing pcrs
376 * - Introduced default_exports() which generates a set of exports
377 * common to all CGIs and other content generators
379 * - Introduced convenience function map_block_killer()
381 * - Introduced convenience function make_menu()
383 * - Introduced CGI-like function error_response() which generates
384 * the "No such domain" and "Connect failed" messages using the
387 * - cgi_show_url_info:
388 * - adapted to new CGI features
389 * - form and answers now generated from same template
390 * - http:// prefix in URL now OK
393 * - adapted to new CGI features
394 * - no longer uses csp->init_proxy_args
397 * - moved menu generation to make_menu()
399 * - add_stats now writes single export map entries instead
402 * - Moved redirect_url() to filters.c
404 * - Fixed mem leak in free_http_response(), map_block_killer(),
406 * - Removed logentry from cancelled commit
408 * Revision 1.7 2001/06/09 10:51:58 jongfoster
409 * Changing "show URL info" handler to new style.
410 * Changing BUFSIZ ==> BUFFER_SIZE
412 * Revision 1.6 2001/06/07 23:05:19 jongfoster
413 * Removing code related to old forward and ACL files.
415 * Revision 1.5 2001/06/05 19:59:16 jongfoster
416 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
418 * Revision 1.4 2001/06/04 10:41:52 swa
419 * show version string of cgi.h and cgi.c
421 * Revision 1.3 2001/06/03 19:12:16 oes
422 * introduced new cgi handling
424 * No revisions before 1.3
426 **********************************************************************/
432 #include <sys/types.h>
440 #define snprintf _snprintf
441 #endif /* def _WIN32 */
449 #include "miscutil.h"
450 #include "cgisimple.h"
451 #ifdef FEATURE_CGI_EDIT_ACTIONS
453 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
455 /* loadcfg.h is for global_toggle_state only */
456 #ifdef FEATURE_PTHREAD
459 /* jcc.h is for mutex semaphore globals only */
460 #endif /* def FEATURE_PTHREAD */
461 const char cgi_h_rcs[] = CGI_H_VERSION;
464 * List of CGI functions: name, handler, description
465 * Note: Do NOT use single quotes in the description;
466 * this will break the dynamic "blocked" template!
468 static const struct cgi_dispatcher cgi_dispatchers[] = {
473 #ifdef FEATURE_GRACEFUL_TERMINATION
476 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
477 "this is a one click Denial Of Service attack!!!</em>",
482 #ifdef FEATURE_CGI_EDIT_ACTIONS
483 "View & change the current configuration",
485 "View the current configuration",
490 "View the source code version numbers",
494 "View the request headers.",
498 "Look up which actions apply to a URL and why",
500 #ifdef FEATURE_CGI_EDIT_ACTIONS
503 "Toggle Privoxy on or off",
505 { "edit-actions", /* Edit the actions list */
508 { "eaa", /* Shortcut for edit-actions-add-url-form */
509 cgi_edit_actions_add_url_form,
511 { "eau", /* Shortcut for edit-actions-url-form */
512 cgi_edit_actions_url_form,
514 { "ear", /* Shortcut for edit-actions-remove-url-form */
515 cgi_edit_actions_remove_url_form,
517 { "eafu", /* Shortcut for edit-actions-for-url */
518 cgi_edit_actions_for_url,
520 { "eas", /* Shortcut for edit-actions-submit */
521 cgi_edit_actions_submit,
523 { "easa", /* Shortcut for edit-actions-section-add */
524 cgi_edit_actions_section_add,
526 { "easr", /* Shortcut for edit-actions-section-remove */
527 cgi_edit_actions_section_remove,
529 { "eass", /* Shortcut for edit-actions-section-swap */
530 cgi_edit_actions_section_swap,
532 { "edit-actions-for-url",
533 cgi_edit_actions_for_url,
534 NULL, FALSE /* Edit the actions for (a) specified URL(s) */ },
535 { "edit-actions-list",
536 cgi_edit_actions_list,
537 NULL, TRUE /* Edit the actions list */ },
538 { "edit-actions-submit",
539 cgi_edit_actions_submit,
540 NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
541 { "edit-actions-url",
542 cgi_edit_actions_url,
543 NULL, FALSE /* Change a URL pattern in the actionsfile */ },
544 { "edit-actions-url-form",
545 cgi_edit_actions_url_form,
546 NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
547 { "edit-actions-add-url",
548 cgi_edit_actions_add_url,
549 NULL, FALSE /* Add a URL pattern to the actionsfile */ },
550 { "edit-actions-add-url-form",
551 cgi_edit_actions_add_url_form,
552 NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
553 { "edit-actions-remove-url",
554 cgi_edit_actions_remove_url,
555 NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
556 { "edit-actions-remove-url-form",
557 cgi_edit_actions_remove_url_form,
558 NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
559 { "edit-actions-section-add",
560 cgi_edit_actions_section_add,
561 NULL, FALSE /* Remove a section from the actionsfile */ },
562 { "edit-actions-section-remove",
563 cgi_edit_actions_section_remove,
564 NULL, FALSE /* Remove a section from the actionsfile */ },
565 { "edit-actions-section-swap",
566 cgi_edit_actions_section_swap,
567 NULL, FALSE /* Swap two sections in the actionsfile */ },
568 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
571 NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ },
574 NULL, TRUE /* Send a built-in image */ },
577 NULL, TRUE /* Send templates/cgi-style.css */ },
579 cgi_transparent_image,
580 NULL, TRUE /* Send a transparent image (short name) */ },
581 { NULL, /* NULL Indicates end of list and default page */
583 NULL, TRUE /* Unknown CGI page */ }
588 * Built-in images for ad replacement
590 * Hint: You can encode your own images like this:
591 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
594 #ifdef FEATURE_NO_GIFS
597 * Checkerboard pattern, as a PNG.
599 const char image_pattern_data[] =
600 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
601 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
602 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
603 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
604 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
605 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
606 "\000\000\000\111\105\116\104\256\102\140\202";
609 * 1x1 transparant PNG.
611 const char image_blank_data[] =
612 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
613 "\000\000\000\004\000\000\000\004\010\006\000\000\000\251\361\236"
614 "\176\000\000\000\007\164\111\115\105\007\322\003\013\020\073\070"
615 "\013\025\036\203\000\000\000\011\160\110\131\163\000\000\013\022"
616 "\000\000\013\022\001\322\335\176\374\000\000\000\004\147\101\115"
617 "\101\000\000\261\217\013\374\141\005\000\000\000\033\111\104\101"
618 "\124\170\332\143\070\161\342\304\207\377\377\377\347\302\150\006"
619 "\144\016\210\146\040\250\002\000\042\305\065\221\270\027\131\110"
620 "\000\000\000\000\111\105\116\104\256\102\140\202";
624 * Checkerboard pattern, as a GIF.
626 const char image_pattern_data[] =
627 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
628 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
629 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
630 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
634 * 1x1 transparant GIF.
636 const char image_blank_data[] =
637 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
638 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
639 "\000\001\000\000\002\002D\001\000;";
642 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
643 const size_t image_blank_length = sizeof(image_blank_data) - 1;
646 static struct http_response cgi_error_memory_response[1];
648 static struct http_response *dispatch_known_cgi(struct client_state * csp,
650 static struct map *parse_cgi_parameters(char *argstring);
653 /*********************************************************************
655 * Function : dispatch_cgi
657 * Description : Checks if a request URL has either the magical
658 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
659 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
660 * http://config.privoxy.org/). If so, it passes
661 * the (rest of the) path onto dispatch_known_cgi, which
662 * calls the relevant CGI handler function.
665 * 1 : csp = Current client state (buffers, headers, etc...)
667 * Returns : http_response if match, NULL if nonmatch or handler fail
669 *********************************************************************/
670 struct http_response *dispatch_cgi(struct client_state *csp)
672 const char *host = csp->http->host;
673 const char *path = csp->http->path;
676 * Should we intercept ?
679 /* Note: "example.com" and "example.com." are equivalent hostnames. */
681 /* Either the host matches CGI_SITE_1_HOST ..*/
682 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
683 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
684 && (path[0] == '/') )
686 /* ..then the path will all be for us. Remove leading '/' */
689 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
690 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
691 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
692 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
694 /* take everything following CGI_SITE_2_PATH */
695 path += strlen(CGI_SITE_2_PATH);
698 /* skip the forward slash after CGI_SITE_2_PATH */
701 else if (*path != '\0')
704 * wierdness: URL is /configXXX, where XXX is some string
705 * Do *NOT* intercept.
717 * This is a CGI call.
720 return dispatch_known_cgi(csp, path);
724 /*********************************************************************
726 * Function : grep_cgi_referrer
728 * Description : Ugly provisorical fix that greps the value of the
729 * referer HTTP header field out of a linked list of
730 * strings like found at csp->headers. Will disappear
733 * FIXME: csp->headers ought to be csp->http->headers
734 * FIXME: Parsing all client header lines should
735 * happen right after the request is received!
738 * 1 : csp = Current client state (buffers, headers, etc...)
740 * Returns : pointer to value (no copy!), or NULL if none found.
742 *********************************************************************/
743 char *grep_cgi_referrer(struct client_state *csp)
745 struct list_entry *p;
747 for (p = csp->headers->first; p != NULL; p = p->next)
749 if (p->str == NULL) continue;
750 if (strncmpic(p->str, "Referer: ", 9) == 0)
752 return ((p->str) + 9);
760 /*********************************************************************
762 * Function : dispatch_known_cgi
764 * Description : Processes a CGI once dispatch_cgi has determined that
765 * it matches one of the magic prefixes. Parses the path
766 * as a cgi name plus query string, prepares a map that
767 * maps CGI parameter names to their values, initializes
768 * the http_response struct, and calls the relevant CGI
772 * 1 : csp = Current client state (buffers, headers, etc...)
773 * 2 : path = Path of CGI, with the CGI prefix removed.
774 * Should not have a leading "/".
776 * Returns : http_response, or NULL on handler failure or out of
779 *********************************************************************/
780 static struct http_response *dispatch_known_cgi(struct client_state * csp,
783 const struct cgi_dispatcher *d;
784 struct map *param_list;
785 struct http_response *rsp;
786 char *query_args_start;
791 if (NULL == (path_copy = strdup(path)))
793 return cgi_error_memory();
796 query_args_start = path_copy;
797 while (*query_args_start && *query_args_start != '?')
801 if (*query_args_start == '?')
803 *query_args_start++ = '\0';
806 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
809 return cgi_error_memory();
814 * path_copy = CGI call name
815 * param_list = CGI params, as map
818 /* Get mem for response or fail*/
819 if (NULL == (rsp = alloc_http_response()))
822 free_map(param_list);
823 return cgi_error_memory();
826 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
827 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
828 csp->ip_addr_str, csp->http->cmd);
831 * Find and start the right CGI function
836 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
839 * If the called CGI is either harmless, or not referred
840 * from an untrusted source, start it.
843 || (NULL == (referrer = grep_cgi_referrer(csp)))
844 || (0 == strncmp(referrer, "http://config.privoxy.org/", 26))
847 err = (d->handler)(csp, rsp, param_list);
852 * Else, modify toggle calls so that they only display
853 * the status, and deny all other calls.
855 if (0 == strcmp(path_copy, "toggle"))
857 unmap(param_list, "set");
858 err = (d->handler)(csp, rsp, param_list);
862 err = cgi_error_404(csp, rsp, param_list);
867 free_map(param_list);
869 if (err == JB_ERR_CGI_PARAMS)
871 err = cgi_error_bad_param(csp, rsp);
873 if (err && (err != JB_ERR_MEMORY))
875 /* Unexpected error! Shouldn't get here */
876 log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler. Please file a bug report!", err);
877 err = cgi_error_unknown(csp, rsp, err);
882 return finish_http_response(rsp);
886 /* Error in handler, probably out-of-memory */
887 free_http_response(rsp);
888 return cgi_error_memory();
896 /*********************************************************************
898 * Function : parse_cgi_parameters
900 * Description : Parse a URL-encoded argument string into name/value
901 * pairs and store them in a struct map list.
904 * 1 : argstring = string to be parsed. Will be trashed.
906 * Returns : pointer to param list, or NULL if out of memory.
908 *********************************************************************/
909 static struct map *parse_cgi_parameters(char *argstring)
912 char *vector[BUFFER_SIZE];
914 struct map *cgi_params;
916 if (NULL == (cgi_params = new_map()))
922 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
923 * the fragment identifier along with the request, so we must
924 * cut it off here, so it won't pollute the CGI params:
926 if (NULL != (p = strchr(argstring, '#')))
931 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
933 for (i = 0; i < pairs; i++)
935 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
938 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
940 free_map(cgi_params);
951 /*********************************************************************
953 * Function : get_char_param
955 * Description : Get a single-character parameter passed to a CGI
959 * 1 : parameters = map of cgi parameters
960 * 2 : param_name = The name of the parameter to read
962 * Returns : Uppercase character on success, '\0' on error.
964 *********************************************************************/
965 char get_char_param(const struct map *parameters,
966 const char *param_name)
973 ch = *(lookup(parameters, param_name));
974 if ((ch >= 'a') && (ch <= 'z'))
983 /*********************************************************************
985 * Function : get_string_param
987 * Description : Get a string paramater, to be used as an
988 * ACTION_STRING or ACTION_MULTI paramater.
989 * Validates the input to prevent stupid/malicious
990 * users from corrupting their action file.
993 * 1 : parameters = map of cgi parameters
994 * 2 : param_name = The name of the parameter to read
995 * 3 : pparam = destination for paramater. Allocated as
996 * part of the map "parameters", so don't free it.
997 * Set to NULL if not specified.
999 * Returns : JB_ERR_OK on success, or if the paramater
1000 * was not specified.
1001 * JB_ERR_MEMORY on out-of-memory.
1002 * JB_ERR_CGI_PARAMS if the paramater is not valid.
1004 *********************************************************************/
1005 jb_err get_string_param(const struct map *parameters,
1006 const char *param_name,
1007 const char **pparam)
1019 param = lookup(parameters, param_name);
1025 if (strlen(param) >= CGI_PARAM_LEN_MAX)
1030 * Note that the length limit is arbitrary, it just seems
1031 * sensible to limit it to *something*. There's no
1032 * technical reason for any limit at all.
1034 return JB_ERR_CGI_PARAMS;
1037 /* Check every character to see if it's legal */
1039 while ((ch = *s++) != '\0')
1041 if ( ((unsigned char)ch < (unsigned char)' ')
1044 /* Probable hack attempt, or user accidentally used '}'. */
1045 return JB_ERR_CGI_PARAMS;
1056 /*********************************************************************
1058 * Function : get_number_param
1060 * Description : Get a non-negative integer from the parameters
1061 * passed to a CGI function.
1064 * 1 : csp = Current client state (buffers, headers, etc...)
1065 * 2 : parameters = map of cgi parameters
1066 * 3 : name = Name of CGI parameter to read
1067 * 4 : pvalue = destination for value.
1068 * Set to -1 on error.
1070 * Returns : JB_ERR_OK on success
1071 * JB_ERR_MEMORY on out-of-memory
1072 * JB_ERR_CGI_PARAMS if the parameter was not specified
1075 *********************************************************************/
1076 jb_err get_number_param(struct client_state *csp,
1077 const struct map *parameters,
1092 param = lookup(parameters, name);
1095 return JB_ERR_CGI_PARAMS;
1098 /* We don't use atoi because I want to check this carefully... */
1101 while ((ch = *param++) != '\0')
1103 if ((ch < '0') || (ch > '9'))
1105 return JB_ERR_CGI_PARAMS;
1112 * <limits.h> defines UINT_MAX
1114 * (UINT_MAX - ch) / 10 is the largest number that
1115 * can be safely multiplied by 10 then have ch added.
1117 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
1119 return JB_ERR_CGI_PARAMS;
1122 value = value * 10 + ch;
1133 /*********************************************************************
1135 * Function : error_response
1137 * Description : returns an http_response that explains the reason
1138 * why a request failed.
1141 * 1 : csp = Current client state (buffers, headers, etc...)
1142 * 2 : templatename = Which template should be used for the answer
1143 * 3 : sys_err = system error number
1145 * Returns : A http_response. If we run out of memory, this
1146 * will be cgi_error_memory().
1148 *********************************************************************/
1149 struct http_response *error_response(struct client_state *csp,
1150 const char *templatename,
1154 struct http_response *rsp;
1155 struct map * exports = default_exports(csp, NULL);
1156 if (exports == NULL)
1158 return cgi_error_memory();
1161 if (NULL == (rsp = alloc_http_response()))
1164 return cgi_error_memory();
1167 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1168 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1169 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1170 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1171 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1174 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1177 /* Some failures, like "404 no such domain", don't have an IP address. */
1178 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1186 free_http_response(rsp);
1187 return cgi_error_memory();
1190 if (!strcmp(templatename, "no-such-domain"))
1192 rsp->status = strdup("404 No such domain");
1193 if (rsp->status == NULL)
1196 free_http_response(rsp);
1197 return cgi_error_memory();
1200 else if (!strcmp(templatename, "connect-failed"))
1202 rsp->status = strdup("503 Connect failed");
1203 if (rsp->status == NULL)
1206 free_http_response(rsp);
1207 return cgi_error_memory();
1211 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1214 free_http_response(rsp);
1215 return cgi_error_memory();
1218 return finish_http_response(rsp);
1222 /*********************************************************************
1224 * Function : cgi_init_error_messages
1226 * Description : Call at the start of the program to initialize
1227 * the error message used by cgi_error_memory().
1233 *********************************************************************/
1234 void cgi_init_error_messages(void)
1236 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1237 cgi_error_memory_response->head =
1238 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1239 "Content-Type: text/html\r\n"
1241 cgi_error_memory_response->body =
1243 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1245 "<h1>500 Internal Privoxy Error</h1>\r\n"
1246 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1247 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1251 cgi_error_memory_response->head_length =
1252 strlen(cgi_error_memory_response->head);
1253 cgi_error_memory_response->content_length =
1254 strlen(cgi_error_memory_response->body);
1258 /*********************************************************************
1260 * Function : cgi_error_memory
1262 * Description : Called if a CGI function runs out of memory.
1263 * Returns a statically-allocated error response.
1267 * Returns : http_response data structure for output. This is
1268 * statically allocated, for obvious reasons.
1270 *********************************************************************/
1271 struct http_response *cgi_error_memory(void)
1273 /* assert that it's been initialized. */
1274 assert(cgi_error_memory_response->head);
1276 return cgi_error_memory_response;
1280 /*********************************************************************
1282 * Function : cgi_error_no_template
1284 * Description : Almost-CGI function that is called if a template
1285 * cannot be loaded. Note this is not a true CGI,
1286 * it takes a template name rather than a map of
1290 * 1 : csp = Current client state (buffers, headers, etc...)
1291 * 2 : rsp = http_response data structure for output
1292 * 3 : template_name = Name of template that could not
1295 * Returns : JB_ERR_OK on success
1296 * JB_ERR_MEMORY on out-of-memory error.
1298 *********************************************************************/
1299 jb_err cgi_error_no_template(struct client_state *csp,
1300 struct http_response *rsp,
1301 const char *template_name)
1303 static const char status[] =
1304 "500 Internal Privoxy Error";
1305 static const char body_prefix[] =
1307 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1309 "<h1>500 Internal Privoxy Error</h1>\r\n"
1310 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1311 "<p><b>Could not load template file <code>";
1312 static const char body_suffix[] =
1313 "</code> or one of it's included components.</b></p>\r\n"
1314 "<p>Please contact your proxy administrator.</p>\r\n"
1315 "<p>If you are the proxy administrator, please put the required file(s)"
1316 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1317 "location of the <code><i>(confdir)</i></code> directory "
1318 "is specified in the main Privoxy <code>config</code> "
1319 "file. (It's typically the Privoxy install directory"
1321 ", or <code>/etc/privoxy/</code>"
1322 #endif /* ndef _WIN32 */
1329 assert(template_name);
1331 /* Reset rsp, if needed */
1335 rsp->content_length = 0;
1336 rsp->head_length = 0;
1339 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1340 if (rsp->body == NULL)
1342 return JB_ERR_MEMORY;
1344 strcpy(rsp->body, body_prefix);
1345 strcat(rsp->body, template_name);
1346 strcat(rsp->body, body_suffix);
1348 rsp->status = strdup(status);
1349 if (rsp->body == NULL)
1351 return JB_ERR_MEMORY;
1358 /*********************************************************************
1360 * Function : cgi_error_unknown
1362 * Description : Almost-CGI function that is called if an unexpected
1363 * error occurs in the top-level CGI dispatcher.
1364 * In this context, "unexpected" means "anything other
1365 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1366 * expected to handle all other errors internally,
1367 * since they can give more relavent error messages
1370 * Note this is not a true CGI, it takes an error
1371 * code rather than a map of parameters.
1374 * 1 : csp = Current client state (buffers, headers, etc...)
1375 * 2 : rsp = http_response data structure for output
1376 * 3 : error_to_report = Error code to report.
1378 * Returns : JB_ERR_OK on success
1379 * JB_ERR_MEMORY on out-of-memory error.
1381 *********************************************************************/
1382 jb_err cgi_error_unknown(struct client_state *csp,
1383 struct http_response *rsp,
1384 jb_err error_to_report)
1386 static const char status[] =
1387 "500 Internal Privoxy Error";
1388 static const char body_prefix[] =
1390 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1392 "<h1>500 Internal Privoxy Error</h1>\r\n"
1393 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1394 "<p><b>Unexpected internal error: ";
1395 static const char body_suffix[] =
1398 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1399 "file a bug report</a>.</p>\r\n"
1406 /* Reset rsp, if needed */
1410 rsp->content_length = 0;
1411 rsp->head_length = 0;
1414 sprintf(errnumbuf, "%d", error_to_report);
1416 rsp->body = malloc(strlen(body_prefix) + strlen(errnumbuf) + strlen(body_suffix) + 1);
1417 if (rsp->body == NULL)
1419 return JB_ERR_MEMORY;
1421 strcpy(rsp->body, body_prefix);
1422 strcat(rsp->body, errnumbuf);
1423 strcat(rsp->body, body_suffix);
1425 rsp->status = strdup(status);
1426 if (rsp->body == NULL)
1428 return JB_ERR_MEMORY;
1435 /*********************************************************************
1437 * Function : cgi_error_bad_param
1439 * Description : CGI function that is called if the parameters
1440 * (query string) for a CGI were wrong.
1443 * 1 : csp = Current client state (buffers, headers, etc...)
1444 * 2 : rsp = http_response data structure for output
1446 * CGI Parameters : none
1448 * Returns : JB_ERR_OK on success
1449 * JB_ERR_MEMORY on out-of-memory error.
1451 *********************************************************************/
1452 jb_err cgi_error_bad_param(struct client_state *csp,
1453 struct http_response *rsp)
1455 struct map *exports;
1460 if (NULL == (exports = default_exports(csp, NULL)))
1462 return JB_ERR_MEMORY;
1465 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1469 /*********************************************************************
1471 * Function : add_help_link
1473 * Description : Produce a copy of the string given as item,
1474 * embedded in an HTML link to its corresponding
1475 * section (item name in uppercase) in the actions
1476 * chapter of the user manual, (whose URL is given in
1477 * the config and defaults to our web site).
1479 * FIXME: I currently only work for actions, and would
1480 * like to be generalized for other topics.
1483 * 1 : item = item (will NOT be free()d.)
1484 * It is assumed to be HTML-safe.
1485 * 2 : config = The current configuration.
1487 * Returns : String with item embedded in link, or NULL on
1490 *********************************************************************/
1491 char *add_help_link(const char *item,
1492 struct configuration_spec *config)
1496 if (!item) return NULL;
1498 result = strdup("<a href=\"");
1499 string_append(&result, config->usermanual);
1500 string_append(&result, ACTIONS_HELP_PREFIX);
1501 string_join (&result, string_toupper(item));
1502 string_append(&result, "\">");
1503 string_append(&result, item);
1504 string_append(&result, "</a> ");
1510 /*********************************************************************
1512 * Function : get_http_time
1514 * Description : Get the time in a format suitable for use in a
1515 * HTTP header - e.g.:
1516 * "Sun, 06 Nov 1994 08:49:37 GMT"
1519 * 1 : time_offset = Time returned will be current time
1520 * plus this number of seconds.
1521 * 2 : buf = Destination for result. Must be long enough
1522 * to hold 29 characters plus a trailing zero.
1526 *********************************************************************/
1527 void get_http_time(int time_offset, char *buf)
1529 static const char day_names[7][4] =
1530 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1531 static const char month_names[12][4] =
1532 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1533 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1536 time_t current_time;
1537 #if defined(HAVE_GMTIME_R) && !defined(OSX_DARWIN)
1539 * Declare dummy up here (instead of inside get/set gmt block) so it
1540 * doesn't go out of scope before it's potentially used in snprintf later.
1541 * Wrapping declaration inside HAVE_GMTIME_R keeps the compiler quiet when
1542 * !defined HAVE_GMTIME_R.
1549 time(¤t_time); /* get current time */
1551 current_time += time_offset;
1553 /* get and save the gmt */
1556 pthread_mutex_lock(&gmtime_mutex);
1557 t = gmtime(¤t_time);
1558 pthread_mutex_unlock(&gmtime_mutex);
1560 t = gmtime_r(¤t_time, &dummy);
1562 t = gmtime(¤t_time);
1566 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1568 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1569 day_names[t->tm_wday],
1571 month_names[t->tm_mon],
1581 /*********************************************************************
1583 * Function : finish_http_response
1585 * Description : Fill in the missing headers in an http response,
1586 * and flatten the headers to an http head.
1589 * 1 : rsp = pointer to http_response to be processed
1591 * Returns : A http_response, usually the rsp parameter.
1592 * On error, free()s rsp and returns cgi_error_memory()
1594 *********************************************************************/
1595 struct http_response *finish_http_response(struct http_response *rsp)
1597 char buf[BUFFER_SIZE];
1600 /* Special case - do NOT change this statically allocated response,
1601 * which is ready for output anyway.
1603 if (rsp == cgi_error_memory_response)
1609 * Fill in the HTTP Status
1611 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1612 err = enlist_first(rsp->headers, buf);
1615 * Set the Content-Length
1617 if (rsp->content_length == 0)
1619 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1623 sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1624 err = enlist(rsp->headers, buf);
1628 * Fill in the default headers:
1630 * Content-Type: default to text/html if not already specified.
1631 * Date: set to current date/time.
1632 * Last-Modified: set to date/time the page was last changed.
1633 * Expires: set to date/time page next needs reloading.
1634 * Cache-Control: set to "no-cache" if applicable.
1636 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1638 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1643 * Set Expires to about 10 min into the future so it'll get reloaded
1644 * occasionally, e.g. if Privoxy gets upgraded.
1649 get_http_time(0, buf);
1650 err = enlist_unique_header(rsp->headers, "Date", buf);
1653 /* Some date in the past. */
1654 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1658 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1659 err = enlist_unique_header(rsp->headers, "Expires", buf);
1665 * Compliant browsers should not cache this due to the "Cache-Control"
1666 * setting. However, to be certain, we also set both "Last-Modified"
1667 * and "Expires" to the current time.
1669 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1671 get_http_time(0, buf);
1672 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1673 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1674 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1681 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1683 free_http_response(rsp);
1684 return cgi_error_memory();
1686 rsp->head_length = strlen(rsp->head);
1693 /*********************************************************************
1695 * Function : alloc_http_response
1697 * Description : Allocates a new http_response structure.
1701 * Returns : pointer to a new http_response, or NULL.
1703 *********************************************************************/
1704 struct http_response *alloc_http_response(void)
1706 return (struct http_response *) zalloc(sizeof(struct http_response));
1711 /*********************************************************************
1713 * Function : free_http_response
1715 * Description : Free the memory occupied by an http_response
1716 * and its depandant structures.
1719 * 1 : rsp = pointer to http_response to be freed
1723 *********************************************************************/
1724 void free_http_response(struct http_response *rsp)
1727 * Must special case cgi_error_memory_response, which is never freed.
1729 if (rsp && (rsp != cgi_error_memory_response))
1734 destroy_list(rsp->headers);
1741 /*********************************************************************
1743 * Function : template_load
1745 * Description : CGI support function that loads a given HTML
1746 * template from the confdir, ignoring comment
1747 * lines and following #include statements up to
1751 * 1 : csp = Current client state (buffers, headers, etc...)
1752 * 2 : template_ptr = Destination for pointer to loaded
1754 * 3 : templatename = name of the HTML template to be used
1755 * 4 : recursive = Flag set if this function calls itself
1756 * following an #include statament
1758 * Returns : JB_ERR_OK on success
1759 * JB_ERR_MEMORY on out-of-memory error.
1760 * JB_ERR_FILE if the template file cannot be read
1762 *********************************************************************/
1763 jb_err template_load(struct client_state *csp, char **template_ptr,
1764 const char *templatename, int recursive)
1767 char *templates_dir_path;
1770 char *included_module;
1773 char buf[BUFFER_SIZE];
1776 assert(template_ptr);
1777 assert(templatename);
1779 *template_ptr = NULL;
1781 /* Validate template name. Paranoia. */
1782 for (p = templatename; *p != 0; p++)
1784 if ( ((*p < 'a') || (*p > 'z'))
1785 && ((*p < 'A') || (*p > 'Z'))
1786 && ((*p < '0') || (*p > '9'))
1790 /* Illegal character */
1795 /* Generate full path */
1797 templates_dir_path = make_path(csp->config->confdir, "templates");
1798 if (templates_dir_path == NULL)
1800 return JB_ERR_MEMORY;
1803 full_path = make_path(templates_dir_path, templatename);
1804 free(templates_dir_path);
1805 if (full_path == NULL)
1807 return JB_ERR_MEMORY;
1810 /* Allocate buffer */
1812 file_buffer = strdup("");
1813 if (file_buffer == NULL)
1816 return JB_ERR_MEMORY;
1819 /* Open template file */
1821 if (NULL == (fp = fopen(full_path, "r")))
1823 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1831 * Read the file, ignoring comments, and honoring #include
1832 * statements, unless we're already called recursively.
1834 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1835 * This is unlikely in practise.
1837 while (fgets(buf, BUFFER_SIZE, fp))
1839 if (!recursive && !strncmp(buf, "#include ", 9))
1841 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1848 if (string_join(&file_buffer, included_module))
1851 return JB_ERR_MEMORY;
1857 /* skip lines starting with '#' */
1863 if (string_append(&file_buffer, buf))
1866 return JB_ERR_MEMORY;
1871 *template_ptr = file_buffer;
1877 /*********************************************************************
1879 * Function : template_fill
1881 * Description : CGI support function that fills in a pre-loaded
1882 * HTML template by replacing @name@ with value using
1883 * pcrs, for each item in the output map.
1885 * Note that a leading '$' charachter in the export map's
1886 * values will be stripped and toggle on backreference
1890 * 1 : template_ptr = IN: Template to be filled out.
1892 * OUT: Filled out template.
1893 * Caller must free().
1894 * 2 : exports = map with fill in symbol -> name pairs
1896 * Returns : JB_ERR_OK on success
1897 * JB_ERR_MEMORY on out-of-memory error
1899 *********************************************************************/
1900 jb_err template_fill(char **template_ptr, const struct map *exports)
1902 struct map_entry *m;
1904 char buf[BUFFER_SIZE];
1905 char *tmp_out_buffer;
1911 assert(template_ptr);
1912 assert(*template_ptr);
1915 file_buffer = *template_ptr;
1916 size = strlen(file_buffer) + 1;
1919 * Assemble pcrs joblist from exports map
1921 for (m = exports->first; m != NULL; m = m->next)
1923 if (*m->name == '$')
1926 * First character of name is '$', so remove this flag
1927 * character and allow backreferences ($1 etc) in the
1928 * "replace with" text.
1930 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1936 * Treat the "replace with" text as a literal string -
1937 * no quoting needed, no backreferences allowed.
1938 * ("Trivial" ['T'] flag).
1942 /* Enclose name in @@ */
1943 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1947 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1949 /* Make and run job. */
1950 job = pcrs_compile(buf, m->value, flags, &error);
1953 if (error == PCRS_ERR_NOMEM)
1956 *template_ptr = NULL;
1957 return JB_ERR_MEMORY;
1961 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1962 /* Hope it wasn't important and silently ignore the invalid job */
1967 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1970 if (NULL == tmp_out_buffer)
1972 *template_ptr = NULL;
1973 return JB_ERR_MEMORY;
1975 file_buffer = tmp_out_buffer;
1982 *template_ptr = file_buffer;
1987 /*********************************************************************
1989 * Function : template_fill_for_cgi
1991 * Description : CGI support function that loads a HTML template
1992 * and fills it in. Handles file-not-found errors
1993 * by sending a HTML error message. For convenience,
1994 * this function also frees the passed "exports" map.
1997 * 1 : csp = Client state
1998 * 2 : templatename = name of the HTML template to be used
1999 * 3 : exports = map with fill in symbol -> name pairs.
2000 * Will be freed by this function.
2001 * 4 : rsp = Response structure to fill in.
2003 * Returns : JB_ERR_OK on success
2004 * JB_ERR_MEMORY on out-of-memory error
2006 *********************************************************************/
2007 jb_err template_fill_for_cgi(struct client_state *csp,
2008 const char *templatename,
2009 struct map *exports,
2010 struct http_response *rsp)
2015 assert(templatename);
2019 err = template_load(csp, &rsp->body, templatename, 0);
2020 if (err == JB_ERR_FILE)
2023 return cgi_error_no_template(csp, rsp, templatename);
2028 return err; /* JB_ERR_MEMORY */
2030 err = template_fill(&rsp->body, exports);
2036 /*********************************************************************
2038 * Function : default_exports
2040 * Description : returns a struct map list that contains exports
2041 * which are common to all CGI functions.
2044 * 1 : csp = Current client state (buffers, headers, etc...)
2045 * 2 : caller = name of CGI who calls us and which should
2046 * be excluded from the generated menu. May be
2048 * Returns : NULL if no memory, else a new map. Caller frees.
2050 *********************************************************************/
2051 struct map *default_exports(const struct client_state *csp, const char *caller)
2055 struct map * exports;
2056 int local_help_exists = 0;
2060 exports = new_map();
2061 if (exports == NULL)
2066 err = map(exports, "version", 1, html_encode(VERSION), 0);
2067 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
2068 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
2069 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2070 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2071 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
2072 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2073 if (!err) err = map(exports, "user-manual", 1, csp->config->usermanual ,1);
2074 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2075 #ifdef FEATURE_TOGGLE
2076 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2078 if (!err) err = map_block_killer(exports, "can-toggle");
2081 snprintf(buf, 20, "%d", csp->config->hport);
2082 if (!err) err = map(exports, "my-port", 1, buf, 1);
2084 if(!strcmp(CODE_STATUS, "stable"))
2086 if (!err) err = map_block_killer(exports, "unstable");
2089 if (csp->config->admin_address != NULL)
2091 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2092 local_help_exists = 1;
2096 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2099 if (csp->config->proxy_info_url != NULL)
2101 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2102 local_help_exists = 1;
2106 if (!err) err = map_block_killer(exports, "have-proxy-info");
2109 if (local_help_exists == 0)
2111 if (!err) err = map_block_killer(exports, "have-help-info");
2124 /*********************************************************************
2126 * Function : map_block_killer
2128 * Description : Convenience function.
2129 * Adds a "killer" for the conditional HTML-template
2130 * block <name>, i.e. a substitution of the regex
2131 * "if-<name>-start.*if-<name>-end" to the given
2135 * 1 : exports = map to extend
2136 * 2 : name = name of conditional block
2138 * Returns : JB_ERR_OK on success
2139 * JB_ERR_MEMORY on out-of-memory error.
2141 *********************************************************************/
2142 jb_err map_block_killer(struct map *exports, const char *name)
2144 char buf[1000]; /* Will do, since the names are hardwired */
2148 assert(strlen(name) < 490);
2150 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
2151 return map(exports, buf, 1, "", 1);
2155 /*********************************************************************
2157 * Function : map_block_keep
2159 * Description : Convenience function. Removes the markers used
2160 * by map-block-killer, to save a few bytes.
2161 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2164 * 1 : exports = map to extend
2165 * 2 : name = name of conditional block
2167 * Returns : JB_ERR_OK on success
2168 * JB_ERR_MEMORY on out-of-memory error.
2170 *********************************************************************/
2171 jb_err map_block_keep(struct map *exports, const char *name)
2174 char buf[500]; /* Will do, since the names are hardwired */
2178 assert(strlen(name) < 490);
2180 snprintf(buf, 500, "if-%s-start", name);
2181 err = map(exports, buf, 1, "", 1);
2188 snprintf(buf, 500, "if-%s-end", name);
2189 return map(exports, buf, 1, "", 1);
2193 /*********************************************************************
2195 * Function : map_conditional
2197 * Description : Convenience function.
2198 * Adds an "if-then-else" for the conditional HTML-template
2199 * block <name>, i.e. a substitution of the form:
2206 * The control structure and one of the alternatives
2210 * 1 : exports = map to extend
2211 * 2 : name = name of conditional block
2212 * 3 : choose_first = nonzero for first, zero for second.
2214 * Returns : JB_ERR_OK on success
2215 * JB_ERR_MEMORY on out-of-memory error.
2217 *********************************************************************/
2218 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2220 char buf[1000]; /* Will do, since the names are hardwired */
2225 assert(strlen(name) < 480);
2227 snprintf(buf, 1000, (choose_first
2228 ? "else-not-%s@.*@endif-%s"
2229 : "if-%s-then@.*@else-not-%s"),
2232 err = map(exports, buf, 1, "", 1);
2238 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
2239 return map(exports, buf, 1, "", 1);
2243 /*********************************************************************
2245 * Function : make_menu
2247 * Description : Returns an HTML-formatted menu of the available
2248 * unhidden CGIs, excluding the one given in <self>
2250 * Parameters : self = name of CGI to leave out, can be NULL for
2253 * Returns : menu string, or NULL on out-of-memory error.
2255 *********************************************************************/
2256 char *make_menu(const char *self)
2258 const struct cgi_dispatcher *d;
2259 char *result = strdup("");
2263 self = "NO-SUCH-CGI!";
2266 /* List available unhidden CGI's and export as "other-cgis" */
2267 for (d = cgi_dispatchers; d->name; d++)
2269 if (d->description && strcmp(d->name, self))
2271 string_append(&result, "<li><a href=\"" CGI_PREFIX);
2272 string_append(&result, d->name);
2273 string_append(&result, "\">");
2274 string_append(&result, d->description);
2275 string_append(&result, "</a></li>");
2283 /*********************************************************************
2285 * Function : dump_map
2287 * Description : HTML-dump a map for debugging (as table)
2290 * 1 : the_map = map to dump
2292 * Returns : string with HTML
2294 *********************************************************************/
2295 char *dump_map(const struct map *the_map)
2297 struct map_entry *cur_entry;
2298 char *ret = strdup("");
2300 string_append(&ret, "<table>\n");
2302 for (cur_entry = the_map->first;
2303 (cur_entry != NULL) && (ret != NULL);
2304 cur_entry = cur_entry->next)
2306 string_append(&ret, "<tr><td><b>");
2307 string_join (&ret, html_encode(cur_entry->name));
2308 string_append(&ret, "</b></td><td>");
2309 string_join (&ret, html_encode(cur_entry->value));
2310 string_append(&ret, "</td></tr>\n");
2313 string_append(&ret, "</table>\n");