1 const char cgi_rcs[] = "$Id: cgi.c,v 1.70.2.5 2003/03/11 11:53: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.5 2003/03/11 11:53:58 oes
42 * Cosmetic: Renamed cryptic variable
44 * Revision 1.70.2.4 2003/03/07 03:41:03 david__schmidt
45 * 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.
47 * Revision 1.70.2.3 2002/11/28 18:14:32 oes
48 * Disable access to critical CGIs via untrusted referrers.
49 * This prevents users from being tricked by malicious websites
50 * into making unintentional configuration changes:
52 * - Added flag to each cgi_dispatcher that allows or denies
54 * - Introduced proviorical function that greps for the
55 * referrer header before regular header parsing happens
56 * - Added safety check to dispatch_known_cgi. CGI is called
57 * if (cgi harmless || no referrer || we are referrer).
58 * Else a) toggle calls are modified not to change status and
59 * b) all other calls are denied.
61 * Revision 1.70.2.2 2002/11/12 16:20:37 oes
62 * Added missing #ifdef FEATURE_TOGGLE around g_bToggleIJB; fixes bug #636651
64 * Revision 1.70.2.1 2002/08/05 11:17:46 oes
65 * Fixed Bug #587820, i.e. added workaround for IE bug that includes fragment identifier in (cgi) query
67 * Revision 1.70 2002/05/19 11:33:20 jongfoster
68 * If a CGI error was not handled, and propogated back to
69 * dispatch_known_cgi(), then it was assumed to be "out of memory".
70 * This gave a very misleading error message.
72 * Now other errors will cause a simple message giving the error
73 * number and asking the user to report a bug.
76 * http://sourceforge.net/tracker/index.php?func=detail
77 * &aid=557905&group_id=11118&atid=111118
79 * Revision 1.69 2002/05/14 21:28:40 oes
80 * - Fixed add_help_link to link to the (now split) actions
81 * part of the config chapter
82 * - Renamed helplink export to actions-help-prefix
84 * Revision 1.68 2002/05/12 21:36:29 jongfoster
85 * Correcting function comments
87 * Revision 1.67 2002/04/30 12:02:07 oes
88 * Nit: updated a comment
90 * Revision 1.66 2002/04/26 18:32:57 jongfoster
91 * Fixing a memory leak on error
93 * Revision 1.65 2002/04/26 12:53:51 oes
94 * - New function add_help_link
95 * - default_exports now exports links to the user manual
96 * and a prefix for links into the config chapter
98 * Revision 1.64 2002/04/24 02:17:21 oes
99 * - Better descriptions for CGIs
100 * - Hide edit-actions, more shortcuts
101 * - Moved get_char_param, get_string_param and get_number_param here
104 * Revision 1.63 2002/04/15 19:06:43 jongfoster
107 * Revision 1.62 2002/04/10 19:59:46 jongfoster
108 * Fixes to #include in templates:
109 * - Didn't close main file if loading an included template fails.
110 * - I'm paranoid and want to disallow "#include /etc/passwd".
112 * Revision 1.61 2002/04/10 13:37:48 oes
113 * Made templates modular: template_load now recursive with max depth 1
115 * Revision 1.60 2002/04/08 20:50:25 swa
118 * Revision 1.59 2002/04/05 15:51:51 oes
119 * - added send-stylesheet CGI
120 * - bugfix: error-pages now get correct request protocol
122 * - kludged CGI descriptions and menu not to break JS syntax
124 * Revision 1.58 2002/03/29 03:33:13 david__schmidt
125 * Fix Mac OSX compiler warnings
127 * Revision 1.57 2002/03/26 22:29:54 swa
128 * we have a new homepage!
130 * Revision 1.56 2002/03/24 17:50:46 jongfoster
131 * Fixing compile error if actions file editor disabled
133 * Revision 1.55 2002/03/24 16:55:06 oes
134 * Making GIF checkerboard transparent
136 * Revision 1.54 2002/03/24 16:18:15 jongfoster
139 * Revision 1.53 2002/03/24 16:06:00 oes
140 * Correct transparency for checkerboard PNG. Thanks, Magnus!
142 * Revision 1.52 2002/03/24 15:23:33 jongfoster
145 * Revision 1.51 2002/03/24 13:25:43 swa
146 * name change related issues
148 * Revision 1.50 2002/03/16 23:54:06 jongfoster
149 * Adding graceful termination feature, to help look for memory leaks.
150 * If you enable this (which, by design, has to be done by hand
151 * editing config.h) and then go to http://i.j.b/die, then the program
152 * will exit cleanly after the *next* request. It should free all the
153 * memory that was used.
155 * Revision 1.49 2002/03/13 00:27:04 jongfoster
158 * Revision 1.48 2002/03/08 17:47:07 jongfoster
161 * Revision 1.47 2002/03/08 16:41:33 oes
162 * Added GIF images again
164 * Revision 1.46 2002/03/07 03:48:38 oes
165 * - Changed built-in images from GIF to PNG
166 * (with regard to Unisys patent issue)
167 * - Added a 4x4 pattern PNG which is less intrusive
168 * than the logo but also clearly marks the deleted banners
170 * Revision 1.45 2002/03/06 22:54:35 jongfoster
171 * Automated function-comment nitpicking.
173 * Revision 1.44 2002/03/05 22:43:45 david__schmidt
174 * - Better error reporting on OS/2
175 * - Fix double-slash comment (oops)
177 * Revision 1.43 2002/03/05 21:33:45 david__schmidt
178 * - Re-enable OS/2 building after new parms were added
179 * - Fix false out of memory report when resolving CGI templates when no IP
180 * address is available of failed attempt (a la no such domain)
182 * Revision 1.42 2002/01/21 00:33:20 jongfoster
183 * Replacing strsav() with the safer string_append() or string_join().
184 * Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
185 * Adding missing html_encode() to error message generators.
186 * Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
188 * Revision 1.41 2002/01/17 20:56:22 jongfoster
189 * Replacing hard references to the URL of the config interface
190 * with #defines from project.h
192 * Revision 1.40 2002/01/09 14:26:46 oes
193 * Added support for thread-safe gmtime_r call.
195 * Revision 1.39 2001/11/16 00:48:13 jongfoster
196 * Fixing a compiler warning
198 * Revision 1.38 2001/11/13 00:31:21 jongfoster
199 * - Adding new CGIs for use by non-JavaScript browsers:
200 * edit-actions-url-form
201 * edit-actions-add-url-form
202 * edit-actions-remove-url-form
203 * - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
206 * Revision 1.37 2001/11/01 14:28:47 david__schmidt
207 * Show enablement/disablement status in almost all templates.
208 * There is a little trickiness here: apparent recursive resolution of
209 * @if-enabled-then@ caused the toggle template to show status out-of-phase with
210 * the actual enablement status. So a similar construct,
211 * @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
214 * Revision 1.36 2001/10/26 17:33:27 oes
217 * Revision 1.35 2001/10/23 21:48:19 jongfoster
218 * Cleaning up error handling in CGI functions - they now send back
219 * a HTML error page and should never cause a FATAL error. (Fixes one
220 * potential source of "denial of service" attacks).
222 * CGI actions file editor that works and is actually useful.
224 * Ability to toggle Junkbuster remotely using a CGI call.
226 * You can turn off both the above features in the main configuration
227 * file, e.g. if you are running a multi-user proxy.
229 * Revision 1.34 2001/10/18 22:22:09 david__schmidt
230 * Only show "Local support" on templates conditionally:
231 * - if either 'admin-address' or 'proxy-info-url' are uncommented in config
232 * - if not, no Local support section appears
234 * Revision 1.33 2001/10/14 22:28:41 jongfoster
235 * Fixing stupid typo.
237 * Revision 1.32 2001/10/14 22:20:18 jongfoster
238 * - Changes to CGI dispatching method to match CGI names exactly,
239 * rather than doing a prefix match.
240 * - No longer need to count the length of the CGI handler names by hand.
241 * - Adding new handler for 404 error when disptching a CGI, if none of
242 * the handlers match.
243 * - Adding new handlers for CGI actionsfile editor.
245 * Revision 1.31 2001/10/10 10:56:39 oes
246 * Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
248 * Revision 1.30 2001/10/02 15:30:57 oes
249 * Introduced show-request cgi
251 * Revision 1.29 2001/09/20 15:47:44 steudten
253 * Fix BUG: Modify int size to size_t size in fill_template()
254 * - removes big trouble on machines where sizeof(int) != sizeof(size_t).
256 * Revision 1.28 2001/09/19 18:00:37 oes
257 * - Deletef time() FIXME (Can't fail under Linux either, if
258 * the argument is guaranteed to be in out address space,
261 * - Pointer notation cosmetics
262 * - Fixed a minor bug in template_fill(): Failiure of
263 * pcrs_execute() now secure.
265 * Revision 1.27 2001/09/16 17:08:54 jongfoster
266 * Moving simple CGI functions from cgi.c to new file cgisimple.c
268 * Revision 1.26 2001/09/16 15:47:37 jongfoster
269 * First version of CGI-based edit interface. This is very much a
270 * work-in-progress, and you can't actually use it to edit anything
271 * yet. You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
272 * to have any effect.
274 * Revision 1.25 2001/09/16 15:02:35 jongfoster
275 * Adding i.j.b/robots.txt.
276 * Inlining add_stats() since it's only ever called from one place.
278 * Revision 1.24 2001/09/16 11:38:01 jongfoster
279 * Splitting fill_template() into 2 functions:
280 * template_load() loads the file
281 * template_fill() performs the PCRS regexps.
282 * This is because the CGI edit interface has a "table row"
283 * template which is used many times in the page - this
284 * change means it's only loaded from disk once.
286 * Revision 1.23 2001/09/16 11:16:05 jongfoster
287 * Better error handling in dispatch_cgi() and parse_cgi_parameters()
289 * Revision 1.22 2001/09/16 11:00:10 jongfoster
290 * New function alloc_http_response, for symmetry with free_http_response
292 * Revision 1.21 2001/09/13 23:53:03 jongfoster
293 * Support for both static and dynamically generated CGI pages.
294 * Correctly setting Last-Modified: and Expires: HTTP headers.
296 * Revision 1.20 2001/09/13 23:40:36 jongfoster
297 * (Cosmetic only) Indentation correction
299 * Revision 1.19 2001/09/13 23:31:25 jongfoster
300 * Moving image data to cgi.c rather than cgi.h.
302 * Revision 1.18 2001/08/05 16:06:20 jongfoster
303 * Modifiying "struct map" so that there are now separate header and
304 * "map_entry" structures. This means that functions which modify a
305 * map no longer need to return a pointer to the modified map.
306 * Also, it no longer reverses the order of the entries (which may be
307 * important with some advanced template substitutions).
309 * Revision 1.17 2001/08/05 15:57:38 oes
310 * Adapted finish_http_response to new list_to_text
312 * Revision 1.16 2001/08/01 21:33:18 jongfoster
313 * Changes to fill_template() that reduce memory usage without having
314 * an impact on performance. I also renamed some variables so as not
315 * to clash with the C++ keywords "new" and "template".
317 * Revision 1.15 2001/08/01 21:19:22 jongfoster
318 * Moving file version information to a separate CGI page.
320 * Revision 1.14 2001/08/01 00:19:03 jongfoster
321 * New function: map_conditional() for an if-then-else syntax.
322 * Changing to use new version of show_defines()
324 * Revision 1.13 2001/07/30 22:08:36 jongfoster
325 * Tidying up #defines:
326 * - All feature #defines are now of the form FEATURE_xxx
327 * - Permanently turned off WIN_GUI_EDIT
328 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
330 * Revision 1.12 2001/07/29 18:47:05 jongfoster
331 * Adding missing #include "loadcfg.h"
333 * Revision 1.11 2001/07/18 17:24:37 oes
334 * Changed to conform to new pcrs interface
336 * Revision 1.10 2001/07/13 13:53:13 oes
337 * Removed all #ifdef PCRS and related code
339 * Revision 1.9 2001/06/29 21:45:41 oes
340 * Indentation, CRLF->LF, Tab-> Space
342 * Revision 1.8 2001/06/29 13:21:46 oes
343 * - Cosmetics: renamed and reordered functions, variables,
344 * texts, improved comments etc
346 * - Removed ij_untrusted_url() The relevant
347 * info is now part of the "untrusted" page,
348 * which is generated by filters.c:trust_url()
350 * - Generators of content now call finish_http_response()
351 * themselves, making jcc.c:chat() a little less
354 * - Removed obsolete "Pragma: no-cache" from our headers
356 * - http_responses now know their head length
358 * - fill_template now uses the new interface to pcrs, so that
359 * - long jobs (like whole files) no longer have to be assembled
360 * in a fixed size buffer
361 * - the new T (trivial) option is used, and the replacement may
362 * contain Perl syntax backrefs without confusing pcrs
364 * - Introduced default_exports() which generates a set of exports
365 * common to all CGIs and other content generators
367 * - Introduced convenience function map_block_killer()
369 * - Introduced convenience function make_menu()
371 * - Introduced CGI-like function error_response() which generates
372 * the "No such domain" and "Connect failed" messages using the
375 * - cgi_show_url_info:
376 * - adapted to new CGI features
377 * - form and answers now generated from same template
378 * - http:// prefix in URL now OK
381 * - adapted to new CGI features
382 * - no longer uses csp->init_proxy_args
385 * - moved menu generation to make_menu()
387 * - add_stats now writes single export map entries instead
390 * - Moved redirect_url() to filters.c
392 * - Fixed mem leak in free_http_response(), map_block_killer(),
394 * - Removed logentry from cancelled commit
396 * Revision 1.7 2001/06/09 10:51:58 jongfoster
397 * Changing "show URL info" handler to new style.
398 * Changing BUFSIZ ==> BUFFER_SIZE
400 * Revision 1.6 2001/06/07 23:05:19 jongfoster
401 * Removing code related to old forward and ACL files.
403 * Revision 1.5 2001/06/05 19:59:16 jongfoster
404 * Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
406 * Revision 1.4 2001/06/04 10:41:52 swa
407 * show version string of cgi.h and cgi.c
409 * Revision 1.3 2001/06/03 19:12:16 oes
410 * introduced new cgi handling
412 * No revisions before 1.3
414 **********************************************************************/
420 #include <sys/types.h>
428 #define snprintf _snprintf
429 #endif /* def _WIN32 */
437 #include "miscutil.h"
438 #include "cgisimple.h"
439 #ifdef FEATURE_CGI_EDIT_ACTIONS
441 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
443 /* loadcfg.h is for global_toggle_state only */
444 #ifdef FEATURE_PTHREAD
447 /* jcc.h is for mutex semaphore globals only */
448 #endif /* def FEATURE_PTHREAD */
449 const char cgi_h_rcs[] = CGI_H_VERSION;
452 * List of CGI functions: name, handler, description
453 * Note: Do NOT use single quotes in the description;
454 * this will break the dynamic "blocked" template!
456 static const struct cgi_dispatcher cgi_dispatchers[] = {
461 #ifdef FEATURE_GRACEFUL_TERMINATION
464 "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
465 "this is a one click Denial Of Service attack!!!</em>",
470 "View & change the current configuration",
474 "View the source code version numbers",
478 "View the request headers.",
482 "Look up which actions apply to a URL and why",
484 #ifdef FEATURE_CGI_EDIT_ACTIONS
487 "Toggle Privoxy on or off",
489 { "edit-actions", /* Edit the actions list */
492 { "eaa", /* Shortcut for edit-actions-add-url-form */
493 cgi_edit_actions_add_url_form,
495 { "eau", /* Shortcut for edit-actions-url-form */
496 cgi_edit_actions_url_form,
498 { "ear", /* Shortcut for edit-actions-remove-url-form */
499 cgi_edit_actions_remove_url_form,
501 { "eafu", /* Shortcut for edit-actions-for-url */
502 cgi_edit_actions_for_url,
504 { "eas", /* Shortcut for edit-actions-submit */
505 cgi_edit_actions_submit,
507 { "easa", /* Shortcut for edit-actions-section-add */
508 cgi_edit_actions_section_add,
510 { "easr", /* Shortcut for edit-actions-section-remove */
511 cgi_edit_actions_section_remove,
513 { "eass", /* Shortcut for edit-actions-section-swap */
514 cgi_edit_actions_section_swap,
516 { "edit-actions-for-url",
517 cgi_edit_actions_for_url,
518 NULL, FALSE /* Edit the actions for (a) specified URL(s) */ },
519 { "edit-actions-list",
520 cgi_edit_actions_list,
521 NULL, TRUE /* Edit the actions list */ },
522 { "edit-actions-submit",
523 cgi_edit_actions_submit,
524 NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
525 { "edit-actions-url",
526 cgi_edit_actions_url,
527 NULL, FALSE /* Change a URL pattern in the actionsfile */ },
528 { "edit-actions-url-form",
529 cgi_edit_actions_url_form,
530 NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
531 { "edit-actions-add-url",
532 cgi_edit_actions_add_url,
533 NULL, FALSE /* Add a URL pattern to the actionsfile */ },
534 { "edit-actions-add-url-form",
535 cgi_edit_actions_add_url_form,
536 NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
537 { "edit-actions-remove-url",
538 cgi_edit_actions_remove_url,
539 NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
540 { "edit-actions-remove-url-form",
541 cgi_edit_actions_remove_url_form,
542 NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
543 { "edit-actions-section-add",
544 cgi_edit_actions_section_add,
545 NULL, FALSE /* Remove a section from the actionsfile */ },
546 { "edit-actions-section-remove",
547 cgi_edit_actions_section_remove,
548 NULL, FALSE /* Remove a section from the actionsfile */ },
549 { "edit-actions-section-swap",
550 cgi_edit_actions_section_swap,
551 NULL, FALSE /* Swap two sections in the actionsfile */ },
552 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
555 NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ },
558 NULL, TRUE /* Send a built-in image */ },
561 NULL, TRUE /* Send templates/cgi-style.css */ },
563 cgi_transparent_image,
564 NULL, TRUE /* Send a transparent image (short name) */ },
565 { NULL, /* NULL Indicates end of list and default page */
567 NULL, TRUE /* Unknown CGI page */ }
572 * Bulit-in images for ad replacement
574 * Hint: You can encode your own images like this:
575 * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
578 #ifdef FEATURE_NO_GIFS
581 * Checkerboard pattern, as a PNG.
583 const char image_pattern_data[] =
584 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
585 "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
586 "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
587 "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
588 "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
589 "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
590 "\000\000\000\111\105\116\104\256\102\140\202";
593 * 1x1 transparant PNG.
595 const char image_blank_data[] =
596 "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
597 "\000\000\000\004\000\000\000\004\010\006\000\000\000\251\361\236"
598 "\176\000\000\000\007\164\111\115\105\007\322\003\013\020\073\070"
599 "\013\025\036\203\000\000\000\011\160\110\131\163\000\000\013\022"
600 "\000\000\013\022\001\322\335\176\374\000\000\000\004\147\101\115"
601 "\101\000\000\261\217\013\374\141\005\000\000\000\033\111\104\101"
602 "\124\170\332\143\070\161\342\304\207\377\377\377\347\302\150\006"
603 "\144\016\210\146\040\250\002\000\042\305\065\221\270\027\131\110"
604 "\000\000\000\000\111\105\116\104\256\102\140\202";
608 * Checkerboard pattern, as a GIF.
610 const char image_pattern_data[] =
611 "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
612 "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
613 "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
614 "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
618 * 1x1 transparant GIF.
620 const char image_blank_data[] =
621 "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
622 "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
623 "\000\001\000\000\002\002D\001\000;";
626 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
627 const size_t image_blank_length = sizeof(image_blank_data) - 1;
630 static struct http_response cgi_error_memory_response[1];
632 static struct http_response *dispatch_known_cgi(struct client_state * csp,
634 static struct map *parse_cgi_parameters(char *argstring);
637 /*********************************************************************
639 * Function : dispatch_cgi
641 * Description : Checks if a request URL has either the magical
642 * hostname CGI_SITE_1_HOST (usually http://p.p/) or
643 * matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
644 * http://config.privoxy.org/). If so, it passes
645 * the (rest of the) path onto dispatch_known_cgi, which
646 * calls the relevant CGI handler function.
649 * 1 : csp = Current client state (buffers, headers, etc...)
651 * Returns : http_response if match, NULL if nonmatch or handler fail
653 *********************************************************************/
654 struct http_response *dispatch_cgi(struct client_state *csp)
656 const char *host = csp->http->host;
657 const char *path = csp->http->path;
660 * Should we intercept ?
663 /* Note: "example.com" and "example.com." are equivalent hostnames. */
665 /* Either the host matches CGI_SITE_1_HOST ..*/
666 if ( ( (0 == strcmpic(host, CGI_SITE_1_HOST))
667 || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
668 && (path[0] == '/') )
670 /* ..then the path will all be for us. Remove leading '/' */
673 /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
674 else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
675 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
676 && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
678 /* take everything following CGI_SITE_2_PATH */
679 path += strlen(CGI_SITE_2_PATH);
682 /* skip the forward slash after CGI_SITE_2_PATH */
685 else if (*path != '\0')
688 * wierdness: URL is /configXXX, where XXX is some string
689 * Do *NOT* intercept.
701 * This is a CGI call.
704 return dispatch_known_cgi(csp, path);
708 /*********************************************************************
710 * Function : grep_cgi_referrer
712 * Description : Ugly provisorical fix that greps the value of the
713 * referer HTTP header field out of a linked list of
714 * strings like found at csp->headers. Will disappear
717 * FIXME: csp->headers ought to be csp->http->headers
718 * FIXME: Parsing all client header lines should
719 * happen right after the request is received!
722 * 1 : csp = Current client state (buffers, headers, etc...)
724 * Returns : pointer to value (no copy!), or NULL if none found.
726 *********************************************************************/
727 char *grep_cgi_referrer(struct client_state *csp)
729 struct list_entry *p;
731 for (p = csp->headers->first; p != NULL; p = p->next)
733 if (p->str == NULL) continue;
734 if (strncmpic(p->str, "Referer: ", 9) == 0)
736 return ((p->str) + 9);
744 /*********************************************************************
746 * Function : dispatch_known_cgi
748 * Description : Processes a CGI once dispatch_cgi has determined that
749 * it matches one of the magic prefixes. Parses the path
750 * as a cgi name plus query string, prepares a map that
751 * maps CGI parameter names to their values, initializes
752 * the http_response struct, and calls the relevant CGI
756 * 1 : csp = Current client state (buffers, headers, etc...)
757 * 2 : path = Path of CGI, with the CGI prefix removed.
758 * Should not have a leading "/".
760 * Returns : http_response, or NULL on handler failure or out of
763 *********************************************************************/
764 static struct http_response *dispatch_known_cgi(struct client_state * csp,
767 const struct cgi_dispatcher *d;
768 struct map *param_list;
769 struct http_response *rsp;
770 char *query_args_start;
775 if (NULL == (path_copy = strdup(path)))
777 return cgi_error_memory();
780 query_args_start = path_copy;
781 while (*query_args_start && *query_args_start != '?')
785 if (*query_args_start == '?')
787 *query_args_start++ = '\0';
790 if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
793 return cgi_error_memory();
798 * path_copy = CGI call name
799 * param_list = CGI params, as map
802 /* Get mem for response or fail*/
803 if (NULL == (rsp = alloc_http_response()))
806 free_map(param_list);
807 return cgi_error_memory();
810 log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
811 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3",
812 csp->ip_addr_str, csp->http->cmd);
815 * Find and start the right CGI function
820 if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
823 * If the called CGI is either harmless, or not referred
824 * from an untrusted source, start it.
827 || (NULL == (referrer = grep_cgi_referrer(csp)))
828 || (0 == strncmp(referrer, "http://config.privoxy.org/", 26))
831 err = (d->handler)(csp, rsp, param_list);
836 * Else, modify toggle calls so that they only display
837 * the status, and deny all other calls.
839 if (0 == strcmp(path_copy, "toggle"))
841 unmap(param_list, "set");
842 err = (d->handler)(csp, rsp, param_list);
846 err = cgi_error_disabled(csp, rsp);
851 free_map(param_list);
853 if (err == JB_ERR_CGI_PARAMS)
855 err = cgi_error_bad_param(csp, rsp);
857 if (err && (err != JB_ERR_MEMORY))
859 /* Unexpected error! Shouldn't get here */
860 log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler. Please file a bug report!", err);
861 err = cgi_error_unknown(csp, rsp, err);
866 return finish_http_response(rsp);
870 /* Error in handler, probably out-of-memory */
871 free_http_response(rsp);
872 return cgi_error_memory();
880 /*********************************************************************
882 * Function : parse_cgi_parameters
884 * Description : Parse a URL-encoded argument string into name/value
885 * pairs and store them in a struct map list.
888 * 1 : argstring = string to be parsed. Will be trashed.
890 * Returns : pointer to param list, or NULL if out of memory.
892 *********************************************************************/
893 static struct map *parse_cgi_parameters(char *argstring)
896 char *vector[BUFFER_SIZE];
898 struct map *cgi_params;
900 if (NULL == (cgi_params = new_map()))
906 * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
907 * the fragment identifier along with the request, so we must
908 * cut it off here, so it won't pollute the CGI params:
910 if (NULL != (p = strchr(argstring, '#')))
915 pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
917 for (i = 0; i < pairs; i++)
919 if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
922 if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
924 free_map(cgi_params);
935 /*********************************************************************
937 * Function : get_char_param
939 * Description : Get a single-character parameter passed to a CGI
943 * 1 : parameters = map of cgi parameters
944 * 2 : param_name = The name of the parameter to read
946 * Returns : Uppercase character on success, '\0' on error.
948 *********************************************************************/
949 char get_char_param(const struct map *parameters,
950 const char *param_name)
957 ch = *(lookup(parameters, param_name));
958 if ((ch >= 'a') && (ch <= 'z'))
967 /*********************************************************************
969 * Function : get_string_param
971 * Description : Get a string paramater, to be used as an
972 * ACTION_STRING or ACTION_MULTI paramater.
973 * Validates the input to prevent stupid/malicious
974 * users from corrupting their action file.
977 * 1 : parameters = map of cgi parameters
978 * 2 : param_name = The name of the parameter to read
979 * 3 : pparam = destination for paramater. Allocated as
980 * part of the map "parameters", so don't free it.
981 * Set to NULL if not specified.
983 * Returns : JB_ERR_OK on success, or if the paramater
985 * JB_ERR_MEMORY on out-of-memory.
986 * JB_ERR_CGI_PARAMS if the paramater is not valid.
988 *********************************************************************/
989 jb_err get_string_param(const struct map *parameters,
990 const char *param_name,
1003 param = lookup(parameters, param_name);
1009 if (strlen(param) >= CGI_PARAM_LEN_MAX)
1014 * Note that the length limit is arbitrary, it just seems
1015 * sensible to limit it to *something*. There's no
1016 * technical reason for any limit at all.
1018 return JB_ERR_CGI_PARAMS;
1021 /* Check every character to see if it's legal */
1023 while ((ch = *s++) != '\0')
1025 if ( ((unsigned char)ch < (unsigned char)' ')
1028 /* Probable hack attempt, or user accidentally used '}'. */
1029 return JB_ERR_CGI_PARAMS;
1040 /*********************************************************************
1042 * Function : get_number_param
1044 * Description : Get a non-negative integer from the parameters
1045 * passed to a CGI function.
1048 * 1 : csp = Current client state (buffers, headers, etc...)
1049 * 2 : parameters = map of cgi parameters
1050 * 3 : name = Name of CGI parameter to read
1051 * 4 : pvalue = destination for value.
1052 * Set to -1 on error.
1054 * Returns : JB_ERR_OK on success
1055 * JB_ERR_MEMORY on out-of-memory
1056 * JB_ERR_CGI_PARAMS if the parameter was not specified
1059 *********************************************************************/
1060 jb_err get_number_param(struct client_state *csp,
1061 const struct map *parameters,
1076 param = lookup(parameters, name);
1079 return JB_ERR_CGI_PARAMS;
1082 /* We don't use atoi because I want to check this carefully... */
1085 while ((ch = *param++) != '\0')
1087 if ((ch < '0') || (ch > '9'))
1089 return JB_ERR_CGI_PARAMS;
1096 * <limits.h> defines UINT_MAX
1098 * (UINT_MAX - ch) / 10 is the largest number that
1099 * can be safely multiplied by 10 then have ch added.
1101 if (value > ((UINT_MAX - (unsigned)ch) / 10U))
1103 return JB_ERR_CGI_PARAMS;
1106 value = value * 10 + ch;
1117 /*********************************************************************
1119 * Function : error_response
1121 * Description : returns an http_response that explains the reason
1122 * why a request failed.
1125 * 1 : csp = Current client state (buffers, headers, etc...)
1126 * 2 : templatename = Which template should be used for the answer
1127 * 3 : sys_err = system error number
1129 * Returns : A http_response. If we run out of memory, this
1130 * will be cgi_error_memory().
1132 *********************************************************************/
1133 struct http_response *error_response(struct client_state *csp,
1134 const char *templatename,
1138 struct http_response *rsp;
1139 struct map * exports = default_exports(csp, NULL);
1140 if (exports == NULL)
1142 return cgi_error_memory();
1145 if (NULL == (rsp = alloc_http_response()))
1148 return cgi_error_memory();
1151 err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1152 if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1153 if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1154 if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1155 if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1);
1158 err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1161 /* Some failures, like "404 no such domain", don't have an IP address. */
1162 err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1170 free_http_response(rsp);
1171 return cgi_error_memory();
1174 if (!strcmp(templatename, "no-such-domain"))
1176 rsp->status = strdup("404 No such domain");
1177 if (rsp->status == NULL)
1180 free_http_response(rsp);
1181 return cgi_error_memory();
1184 else if (!strcmp(templatename, "connect-failed"))
1186 rsp->status = strdup("503 Connect failed");
1187 if (rsp->status == NULL)
1190 free_http_response(rsp);
1191 return cgi_error_memory();
1195 err = template_fill_for_cgi(csp, templatename, exports, rsp);
1198 free_http_response(rsp);
1199 return cgi_error_memory();
1202 return finish_http_response(rsp);
1206 /*********************************************************************
1208 * Function : cgi_init_error_messages
1210 * Description : Call at the start of the program to initialize
1211 * the error message used by cgi_error_memory().
1217 *********************************************************************/
1218 void cgi_init_error_messages(void)
1220 memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1221 cgi_error_memory_response->head =
1222 "HTTP/1.0 500 Internal Privoxy Error\r\n"
1223 "Content-Type: text/html\r\n"
1225 cgi_error_memory_response->body =
1227 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1229 "<h1>500 Internal Privoxy Error</h1>\r\n"
1230 "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1231 "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1235 cgi_error_memory_response->head_length =
1236 strlen(cgi_error_memory_response->head);
1237 cgi_error_memory_response->content_length =
1238 strlen(cgi_error_memory_response->body);
1242 /*********************************************************************
1244 * Function : cgi_error_memory
1246 * Description : Called if a CGI function runs out of memory.
1247 * Returns a statically-allocated error response.
1251 * Returns : http_response data structure for output. This is
1252 * statically allocated, for obvious reasons.
1254 *********************************************************************/
1255 struct http_response *cgi_error_memory(void)
1257 /* assert that it's been initialized. */
1258 assert(cgi_error_memory_response->head);
1260 return cgi_error_memory_response;
1264 /*********************************************************************
1266 * Function : cgi_error_no_template
1268 * Description : Almost-CGI function that is called if a template
1269 * cannot be loaded. Note this is not a true CGI,
1270 * it takes a template name rather than a map of
1274 * 1 : csp = Current client state (buffers, headers, etc...)
1275 * 2 : rsp = http_response data structure for output
1276 * 3 : template_name = Name of template that could not
1279 * Returns : JB_ERR_OK on success
1280 * JB_ERR_MEMORY on out-of-memory error.
1282 *********************************************************************/
1283 jb_err cgi_error_no_template(struct client_state *csp,
1284 struct http_response *rsp,
1285 const char *template_name)
1287 static const char status[] =
1288 "500 Internal Privoxy Error";
1289 static const char body_prefix[] =
1291 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1293 "<h1>500 Internal Privoxy Error</h1>\r\n"
1294 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1295 "<p><b>Could not load template file <code>";
1296 static const char body_suffix[] =
1297 "</code> or one of it's included components.</b></p>\r\n"
1298 "<p>Please contact your proxy administrator.</p>\r\n"
1299 "<p>If you are the proxy administrator, please put the required file(s)"
1300 "in the <code><i>(confdir)</i>/templates</code> directory. The "
1301 "location of the <code><i>(confdir)</i></code> directory "
1302 "is specified in the main Privoxy <code>config</code> "
1303 "file. (It's typically the Privoxy install directory"
1305 ", or <code>/etc/privoxy/</code>"
1306 #endif /* ndef _WIN32 */
1313 assert(template_name);
1315 /* Reset rsp, if needed */
1319 rsp->content_length = 0;
1320 rsp->head_length = 0;
1323 rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1324 if (rsp->body == NULL)
1326 return JB_ERR_MEMORY;
1328 strcpy(rsp->body, body_prefix);
1329 strcat(rsp->body, template_name);
1330 strcat(rsp->body, body_suffix);
1332 rsp->status = strdup(status);
1333 if (rsp->body == NULL)
1335 return JB_ERR_MEMORY;
1342 /*********************************************************************
1344 * Function : cgi_error_unknown
1346 * Description : Almost-CGI function that is called if an unexpected
1347 * error occurs in the top-level CGI dispatcher.
1348 * In this context, "unexpected" means "anything other
1349 * than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1350 * expected to handle all other errors internally,
1351 * since they can give more relavent error messages
1354 * Note this is not a true CGI, it takes an error
1355 * code rather than a map of parameters.
1358 * 1 : csp = Current client state (buffers, headers, etc...)
1359 * 2 : rsp = http_response data structure for output
1360 * 3 : error_to_report = Error code to report.
1362 * Returns : JB_ERR_OK on success
1363 * JB_ERR_MEMORY on out-of-memory error.
1365 *********************************************************************/
1366 jb_err cgi_error_unknown(struct client_state *csp,
1367 struct http_response *rsp,
1368 jb_err error_to_report)
1370 static const char status[] =
1371 "500 Internal Privoxy Error";
1372 static const char body_prefix[] =
1374 "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1376 "<h1>500 Internal Privoxy Error</h1>\r\n"
1377 "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1378 "<p><b>Unexpected internal error: ";
1379 static const char body_suffix[] =
1382 "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1383 "file a bug report</a>.</p>\r\n"
1390 /* Reset rsp, if needed */
1394 rsp->content_length = 0;
1395 rsp->head_length = 0;
1398 sprintf(errnumbuf, "%d", error_to_report);
1400 rsp->body = malloc(strlen(body_prefix) + strlen(errnumbuf) + strlen(body_suffix) + 1);
1401 if (rsp->body == NULL)
1403 return JB_ERR_MEMORY;
1405 strcpy(rsp->body, body_prefix);
1406 strcat(rsp->body, errnumbuf);
1407 strcat(rsp->body, body_suffix);
1409 rsp->status = strdup(status);
1410 if (rsp->body == NULL)
1412 return JB_ERR_MEMORY;
1419 /*********************************************************************
1421 * Function : cgi_error_bad_param
1423 * Description : CGI function that is called if the parameters
1424 * (query string) for a CGI were wrong.
1427 * 1 : csp = Current client state (buffers, headers, etc...)
1428 * 2 : rsp = http_response data structure for output
1430 * CGI Parameters : none
1432 * Returns : JB_ERR_OK on success
1433 * JB_ERR_MEMORY on out-of-memory error.
1435 *********************************************************************/
1436 jb_err cgi_error_bad_param(struct client_state *csp,
1437 struct http_response *rsp)
1439 struct map *exports;
1444 if (NULL == (exports = default_exports(csp, NULL)))
1446 return JB_ERR_MEMORY;
1449 return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1453 /*********************************************************************
1455 * Function : add_help_link
1457 * Description : Produce a copy of the string given as item,
1458 * embedded in an HTML link to its corresponding
1459 * section (item name in uppercase) in the actions
1460 * chapter of the user manual, (whose URL is given in
1461 * the config and defaults to our web site).
1463 * FIXME: I currently only work for actions, and would
1464 * like to be generalized for other topics.
1467 * 1 : item = item (will NOT be free()d.)
1468 * It is assumed to be HTML-safe.
1469 * 2 : config = The current configuration.
1471 * Returns : String with item embedded in link, or NULL on
1474 *********************************************************************/
1475 char *add_help_link(const char *item,
1476 struct configuration_spec *config)
1480 if (!item) return NULL;
1482 result = strdup("<a href=\"");
1483 string_append(&result, config->usermanual);
1484 string_append(&result, ACTIONS_HELP_PREFIX);
1485 string_join (&result, string_toupper(item));
1486 string_append(&result, "\">");
1487 string_append(&result, item);
1488 string_append(&result, "</a> ");
1494 /*********************************************************************
1496 * Function : get_http_time
1498 * Description : Get the time in a format suitable for use in a
1499 * HTTP header - e.g.:
1500 * "Sun, 06 Nov 1994 08:49:37 GMT"
1503 * 1 : time_offset = Time returned will be current time
1504 * plus this number of seconds.
1505 * 2 : buf = Destination for result. Must be long enough
1506 * to hold 29 characters plus a trailing zero.
1510 *********************************************************************/
1511 void get_http_time(int time_offset, char *buf)
1513 static const char day_names[7][4] =
1514 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1515 static const char month_names[12][4] =
1516 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1517 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1520 time_t current_time;
1521 #ifdef HAVE_GMTIME_R
1523 * Declare dummy up here (instead of inside get/set gmt block) so it
1524 * doesn't go out of scope before it's potentially used in snprintf later.
1525 * Wrapping declaration inside HAVE_GMTIME_R keeps the compiler quiet when
1526 * !defined HAVE_GMTIME_R.
1533 time(¤t_time); /* get current time */
1535 current_time += time_offset;
1537 /* get and save the gmt */
1540 pthread_mutex_lock(&gmtime_mutex);
1541 t = gmtime(¤t_time);
1542 pthread_mutex_unlock(&gmtime_mutex);
1544 t = gmtime_r(¤t_time, &dummy);
1546 t = gmtime(¤t_time);
1550 /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1552 "%s, %02d %s %4d %02d:%02d:%02d GMT",
1553 day_names[t->tm_wday],
1555 month_names[t->tm_mon],
1565 /*********************************************************************
1567 * Function : finish_http_response
1569 * Description : Fill in the missing headers in an http response,
1570 * and flatten the headers to an http head.
1573 * 1 : rsp = pointer to http_response to be processed
1575 * Returns : A http_response, usually the rsp parameter.
1576 * On error, free()s rsp and returns cgi_error_memory()
1578 *********************************************************************/
1579 struct http_response *finish_http_response(struct http_response *rsp)
1581 char buf[BUFFER_SIZE];
1584 /* Special case - do NOT change this statically allocated response,
1585 * which is ready for output anyway.
1587 if (rsp == cgi_error_memory_response)
1593 * Fill in the HTTP Status
1595 sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1596 err = enlist_first(rsp->headers, buf);
1599 * Set the Content-Length
1601 if (rsp->content_length == 0)
1603 rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1607 sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1608 err = enlist(rsp->headers, buf);
1612 * Fill in the default headers:
1614 * Content-Type: default to text/html if not already specified.
1615 * Date: set to current date/time.
1616 * Last-Modified: set to date/time the page was last changed.
1617 * Expires: set to date/time page next needs reloading.
1618 * Cache-Control: set to "no-cache" if applicable.
1620 * See http://www.w3.org/Protocols/rfc2068/rfc2068
1622 if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1627 * Set Expires to about 10 min into the future so it'll get reloaded
1628 * occasionally, e.g. if Privoxy gets upgraded.
1633 get_http_time(0, buf);
1634 err = enlist_unique_header(rsp->headers, "Date", buf);
1637 /* Some date in the past. */
1638 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
1642 get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1643 err = enlist_unique_header(rsp->headers, "Expires", buf);
1649 * Compliant browsers should not cache this due to the "Cache-Control"
1650 * setting. However, to be certain, we also set both "Last-Modified"
1651 * and "Expires" to the current time.
1653 if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1655 get_http_time(0, buf);
1656 if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
1657 if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
1658 if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1665 if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1667 free_http_response(rsp);
1668 return cgi_error_memory();
1670 rsp->head_length = strlen(rsp->head);
1677 /*********************************************************************
1679 * Function : alloc_http_response
1681 * Description : Allocates a new http_response structure.
1685 * Returns : pointer to a new http_response, or NULL.
1687 *********************************************************************/
1688 struct http_response *alloc_http_response(void)
1690 return (struct http_response *) zalloc(sizeof(struct http_response));
1695 /*********************************************************************
1697 * Function : free_http_response
1699 * Description : Free the memory occupied by an http_response
1700 * and its depandant structures.
1703 * 1 : rsp = pointer to http_response to be freed
1707 *********************************************************************/
1708 void free_http_response(struct http_response *rsp)
1711 * Must special case cgi_error_memory_response, which is never freed.
1713 if (rsp && (rsp != cgi_error_memory_response))
1718 destroy_list(rsp->headers);
1725 /*********************************************************************
1727 * Function : template_load
1729 * Description : CGI support function that loads a given HTML
1730 * template from the confdir, ignoring comment
1731 * lines and following #include statements up to
1735 * 1 : csp = Current client state (buffers, headers, etc...)
1736 * 2 : template_ptr = Destination for pointer to loaded
1738 * 3 : templatename = name of the HTML template to be used
1739 * 4 : recursive = Flag set if this function calls itself
1740 * following an #include statament
1742 * Returns : JB_ERR_OK on success
1743 * JB_ERR_MEMORY on out-of-memory error.
1744 * JB_ERR_FILE if the template file cannot be read
1746 *********************************************************************/
1747 jb_err template_load(struct client_state *csp, char **template_ptr,
1748 const char *templatename, int recursive)
1751 char *templates_dir_path;
1754 char *included_module;
1757 char buf[BUFFER_SIZE];
1760 assert(template_ptr);
1761 assert(templatename);
1763 *template_ptr = NULL;
1765 /* Validate template name. Paranoia. */
1766 for (p = templatename; *p != 0; p++)
1768 if ( ((*p < 'a') || (*p > 'z'))
1769 && ((*p < 'A') || (*p > 'Z'))
1770 && ((*p < '0') || (*p > '9'))
1774 /* Illegal character */
1779 /* Generate full path */
1781 templates_dir_path = make_path(csp->config->confdir, "templates");
1782 if (templates_dir_path == NULL)
1784 return JB_ERR_MEMORY;
1787 full_path = make_path(templates_dir_path, templatename);
1788 free(templates_dir_path);
1789 if (full_path == NULL)
1791 return JB_ERR_MEMORY;
1794 /* Allocate buffer */
1796 file_buffer = strdup("");
1797 if (file_buffer == NULL)
1800 return JB_ERR_MEMORY;
1803 /* Open template file */
1805 if (NULL == (fp = fopen(full_path, "r")))
1807 log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1815 * Read the file, ignoring comments, and honoring #include
1816 * statements, unless we're already called recursively.
1818 * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1819 * This is unlikely in practise.
1821 while (fgets(buf, BUFFER_SIZE, fp))
1823 if (!recursive && !strncmp(buf, "#include ", 9))
1825 if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1832 if (string_join(&file_buffer, included_module))
1835 return JB_ERR_MEMORY;
1841 /* skip lines starting with '#' */
1847 if (string_append(&file_buffer, buf))
1850 return JB_ERR_MEMORY;
1855 *template_ptr = file_buffer;
1861 /*********************************************************************
1863 * Function : template_fill
1865 * Description : CGI support function that fills in a pre-loaded
1866 * HTML template by replacing @name@ with value using
1867 * pcrs, for each item in the output map.
1869 * Note that a leading '$' charachter in the export map's
1870 * values will be stripped and toggle on backreference
1874 * 1 : template_ptr = IN: Template to be filled out.
1876 * OUT: Filled out template.
1877 * Caller must free().
1878 * 2 : exports = map with fill in symbol -> name pairs
1880 * Returns : JB_ERR_OK on success
1881 * JB_ERR_MEMORY on out-of-memory error
1883 *********************************************************************/
1884 jb_err template_fill(char **template_ptr, const struct map *exports)
1886 struct map_entry *m;
1888 char buf[BUFFER_SIZE];
1889 char *tmp_out_buffer;
1895 assert(template_ptr);
1896 assert(*template_ptr);
1899 file_buffer = *template_ptr;
1900 size = strlen(file_buffer) + 1;
1903 * Assemble pcrs joblist from exports map
1905 for (m = exports->first; m != NULL; m = m->next)
1907 if (*m->name == '$')
1910 * First character of name is '$', so remove this flag
1911 * character and allow backreferences ($1 etc) in the
1912 * "replace with" text.
1914 snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1920 * Treat the "replace with" text as a literal string -
1921 * no quoting needed, no backreferences allowed.
1922 * ("Trivial" ['T'] flag).
1926 /* Enclose name in @@ */
1927 snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1931 log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1933 /* Make and run job. */
1934 job = pcrs_compile(buf, m->value, flags, &error);
1937 if (error == PCRS_ERR_NOMEM)
1940 *template_ptr = NULL;
1941 return JB_ERR_MEMORY;
1945 log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
1946 /* Hope it wasn't important and silently ignore the invalid job */
1951 pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1954 if (NULL == tmp_out_buffer)
1956 *template_ptr = NULL;
1957 return JB_ERR_MEMORY;
1959 file_buffer = tmp_out_buffer;
1966 *template_ptr = file_buffer;
1971 /*********************************************************************
1973 * Function : template_fill_for_cgi
1975 * Description : CGI support function that loads a HTML template
1976 * and fills it in. Handles file-not-found errors
1977 * by sending a HTML error message. For convenience,
1978 * this function also frees the passed "exports" map.
1981 * 1 : csp = Client state
1982 * 2 : templatename = name of the HTML template to be used
1983 * 3 : exports = map with fill in symbol -> name pairs.
1984 * Will be freed by this function.
1985 * 4 : rsp = Response structure to fill in.
1987 * Returns : JB_ERR_OK on success
1988 * JB_ERR_MEMORY on out-of-memory error
1990 *********************************************************************/
1991 jb_err template_fill_for_cgi(struct client_state *csp,
1992 const char *templatename,
1993 struct map *exports,
1994 struct http_response *rsp)
1999 assert(templatename);
2003 err = template_load(csp, &rsp->body, templatename, 0);
2004 if (err == JB_ERR_FILE)
2007 return cgi_error_no_template(csp, rsp, templatename);
2012 return err; /* JB_ERR_MEMORY */
2014 err = template_fill(&rsp->body, exports);
2020 /*********************************************************************
2022 * Function : default_exports
2024 * Description : returns a struct map list that contains exports
2025 * which are common to all CGI functions.
2028 * 1 : csp = Current client state (buffers, headers, etc...)
2029 * 2 : caller = name of CGI who calls us and which should
2030 * be excluded from the generated menu. May be
2032 * Returns : NULL if no memory, else a new map. Caller frees.
2034 *********************************************************************/
2035 struct map *default_exports(const struct client_state *csp, const char *caller)
2039 struct map * exports;
2040 int local_help_exists = 0;
2044 exports = new_map();
2045 if (exports == NULL)
2050 err = map(exports, "version", 1, html_encode(VERSION), 0);
2051 if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
2052 if (!err) err = map(exports, "my-hostname", 1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
2053 if (!err) err = map(exports, "homepage", 1, html_encode(HOME_PAGE_URL), 0);
2054 if (!err) err = map(exports, "default-cgi", 1, html_encode(CGI_PREFIX), 0);
2055 if (!err) err = map(exports, "menu", 1, make_menu(caller), 0);
2056 if (!err) err = map(exports, "code-status", 1, CODE_STATUS, 1);
2057 if (!err) err = map(exports, "user-manual", 1, csp->config->usermanual ,1);
2058 if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2059 #ifdef FEATURE_TOGGLE
2060 if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2063 snprintf(buf, 20, "%d", csp->config->hport);
2064 if (!err) err = map(exports, "my-port", 1, buf, 1);
2066 if(!strcmp(CODE_STATUS, "stable"))
2068 if (!err) err = map_block_killer(exports, "unstable");
2071 if (csp->config->admin_address != NULL)
2073 if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2074 local_help_exists = 1;
2078 if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2081 if (csp->config->proxy_info_url != NULL)
2083 if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2084 local_help_exists = 1;
2088 if (!err) err = map_block_killer(exports, "have-proxy-info");
2091 if (local_help_exists == 0)
2093 if (!err) err = map_block_killer(exports, "have-help-info");
2106 /*********************************************************************
2108 * Function : map_block_killer
2110 * Description : Convenience function.
2111 * Adds a "killer" for the conditional HTML-template
2112 * block <name>, i.e. a substitution of the regex
2113 * "if-<name>-start.*if-<name>-end" to the given
2117 * 1 : exports = map to extend
2118 * 2 : name = name of conditional block
2120 * Returns : JB_ERR_OK on success
2121 * JB_ERR_MEMORY on out-of-memory error.
2123 *********************************************************************/
2124 jb_err map_block_killer(struct map *exports, const char *name)
2126 char buf[1000]; /* Will do, since the names are hardwired */
2130 assert(strlen(name) < 490);
2132 snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
2133 return map(exports, buf, 1, "", 1);
2137 /*********************************************************************
2139 * Function : map_block_keep
2141 * Description : Convenience function. Removes the markers used
2142 * by map-block-killer, to save a few bytes.
2143 * i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2146 * 1 : exports = map to extend
2147 * 2 : name = name of conditional block
2149 * Returns : JB_ERR_OK on success
2150 * JB_ERR_MEMORY on out-of-memory error.
2152 *********************************************************************/
2153 jb_err map_block_keep(struct map *exports, const char *name)
2156 char buf[500]; /* Will do, since the names are hardwired */
2160 assert(strlen(name) < 490);
2162 snprintf(buf, 500, "if-%s-start", name);
2163 err = map(exports, buf, 1, "", 1);
2170 snprintf(buf, 500, "if-%s-end", name);
2171 return map(exports, buf, 1, "", 1);
2175 /*********************************************************************
2177 * Function : map_conditional
2179 * Description : Convenience function.
2180 * Adds an "if-then-else" for the conditional HTML-template
2181 * block <name>, i.e. a substitution of the form:
2188 * The control structure and one of the alternatives
2192 * 1 : exports = map to extend
2193 * 2 : name = name of conditional block
2194 * 3 : choose_first = nonzero for first, zero for second.
2196 * Returns : JB_ERR_OK on success
2197 * JB_ERR_MEMORY on out-of-memory error.
2199 *********************************************************************/
2200 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2202 char buf[1000]; /* Will do, since the names are hardwired */
2207 assert(strlen(name) < 480);
2209 snprintf(buf, 1000, (choose_first
2210 ? "else-not-%s@.*@endif-%s"
2211 : "if-%s-then@.*@else-not-%s"),
2214 err = map(exports, buf, 1, "", 1);
2220 snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
2221 return map(exports, buf, 1, "", 1);
2225 /*********************************************************************
2227 * Function : make_menu
2229 * Description : Returns an HTML-formatted menu of the available
2230 * unhidden CGIs, excluding the one given in <self>
2232 * Parameters : self = name of CGI to leave out, can be NULL for
2235 * Returns : menu string, or NULL on out-of-memory error.
2237 *********************************************************************/
2238 char *make_menu(const char *self)
2240 const struct cgi_dispatcher *d;
2241 char *result = strdup("");
2245 self = "NO-SUCH-CGI!";
2248 /* List available unhidden CGI's and export as "other-cgis" */
2249 for (d = cgi_dispatchers; d->name; d++)
2251 if (d->description && strcmp(d->name, self))
2253 string_append(&result, "<li><a href=\"" CGI_PREFIX);
2254 string_append(&result, d->name);
2255 string_append(&result, "\">");
2256 string_append(&result, d->description);
2257 string_append(&result, "</a></li>");
2265 /*********************************************************************
2267 * Function : dump_map
2269 * Description : HTML-dump a map for debugging (as table)
2272 * 1 : the_map = map to dump
2274 * Returns : string with HTML
2276 *********************************************************************/
2277 char *dump_map(const struct map *the_map)
2279 struct map_entry *cur_entry;
2280 char *ret = strdup("");
2282 string_append(&ret, "<table>\n");
2284 for (cur_entry = the_map->first;
2285 (cur_entry != NULL) && (ret != NULL);
2286 cur_entry = cur_entry->next)
2288 string_append(&ret, "<tr><td><b>");
2289 string_join (&ret, html_encode(cur_entry->name));
2290 string_append(&ret, "</b></td><td>");
2291 string_join (&ret, html_encode(cur_entry->value));
2292 string_append(&ret, "</td></tr>\n");
2295 string_append(&ret, "</table>\n");