Added documentation for new --chroot option
[privoxy.git] / cgi.c
1 const char cgi_rcs[] = "$Id: cgi.c,v 1.70.2.5 2003/03/11 11:53:58 oes Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/Attic/cgi.c,v $
5  *
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.
10  *                
11  *                Functions declared include:
12  * 
13  *
14  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
15  *                Privoxy team. http://www.privoxy.org/
16  *
17  *                Based on the Internet Junkbuster originally written
18  *                by and Copyright (C) 1997 Anonymous Coders and 
19  *                Junkbusters Corporation.  http://www.junkbusters.com
20  *
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.
26  *
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.
32  *
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.
38  *
39  * Revisions   :
40  *    $Log: cgi.c,v $
41  *    Revision 1.70.2.5  2003/03/11 11:53:58  oes
42  *    Cosmetic: Renamed cryptic variable
43  *
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.
46  *
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:
51  *
52  *     - Added flag to each cgi_dispatcher that allows or denies
53  *       external linking
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.
60  *
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
63  *
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
66  *
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.
71  *
72  *    Now other errors will cause a simple message giving the error
73  *    number and asking the user to report a bug.
74  *
75  *    Bug report:
76  *    http://sourceforge.net/tracker/index.php?func=detail
77  *    &aid=557905&group_id=11118&atid=111118
78  *
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
83  *
84  *    Revision 1.68  2002/05/12 21:36:29  jongfoster
85  *    Correcting function comments
86  *
87  *    Revision 1.67  2002/04/30 12:02:07  oes
88  *    Nit: updated a comment
89  *
90  *    Revision 1.66  2002/04/26 18:32:57  jongfoster
91  *    Fixing a memory leak on error
92  *
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
97  *
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
102  *       from cgiedit.c
103  *
104  *    Revision 1.63  2002/04/15 19:06:43  jongfoster
105  *    Typos
106  *
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".
111  *
112  *    Revision 1.61  2002/04/10 13:37:48  oes
113  *    Made templates modular: template_load now recursive with max depth 1
114  *
115  *    Revision 1.60  2002/04/08 20:50:25  swa
116  *    fixed JB spelling
117  *
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
121  *     - fixed
122  *     - kludged CGI descriptions and menu not to break JS syntax
123  *
124  *    Revision 1.58  2002/03/29 03:33:13  david__schmidt
125  *    Fix Mac OSX compiler warnings
126  *
127  *    Revision 1.57  2002/03/26 22:29:54  swa
128  *    we have a new homepage!
129  *
130  *    Revision 1.56  2002/03/24 17:50:46  jongfoster
131  *    Fixing compile error if actions file editor disabled
132  *
133  *    Revision 1.55  2002/03/24 16:55:06  oes
134  *    Making GIF checkerboard transparent
135  *
136  *    Revision 1.54  2002/03/24 16:18:15  jongfoster
137  *    Removing old logo
138  *
139  *    Revision 1.53  2002/03/24 16:06:00  oes
140  *    Correct transparency for checkerboard PNG. Thanks, Magnus!
141  *
142  *    Revision 1.52  2002/03/24 15:23:33  jongfoster
143  *    Name changes
144  *
145  *    Revision 1.51  2002/03/24 13:25:43  swa
146  *    name change related issues
147  *
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.
154  *
155  *    Revision 1.49  2002/03/13 00:27:04  jongfoster
156  *    Killing warnings
157  *
158  *    Revision 1.48  2002/03/08 17:47:07  jongfoster
159  *    Adding comments
160  *
161  *    Revision 1.47  2002/03/08 16:41:33  oes
162  *    Added GIF images again
163  *
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
169  *
170  *    Revision 1.45  2002/03/06 22:54:35  jongfoster
171  *    Automated function-comment nitpicking.
172  *
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)
176  *
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)
181  *
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.
187  *
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
191  *
192  *    Revision 1.40  2002/01/09 14:26:46  oes
193  *    Added support for thread-safe gmtime_r call.
194  *
195  *    Revision 1.39  2001/11/16 00:48:13  jongfoster
196  *    Fixing a compiler warning
197  *
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.
204  *    - Fixing || bug.
205  *
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'
212  *    templates.
213  *
214  *    Revision 1.36  2001/10/26 17:33:27  oes
215  *    marginal bugfix
216  *
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).
221  *
222  *    CGI actions file editor that works and is actually useful.
223  *
224  *    Ability to toggle Junkbuster remotely using a CGI call.
225  *
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.
228  *
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
233  *
234  *    Revision 1.33  2001/10/14 22:28:41  jongfoster
235  *    Fixing stupid typo.
236  *
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.
244  *
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
247  *
248  *    Revision 1.30  2001/10/02 15:30:57  oes
249  *    Introduced show-request cgi
250  *
251  *    Revision 1.29  2001/09/20 15:47:44  steudten
252  *
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).
255  *
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,
259  *       which it is.)
260  *     - Fixed comments
261  *     - Pointer notation cosmetics
262  *     - Fixed a minor bug in template_fill(): Failiure of
263  *       pcrs_execute() now secure.
264  *
265  *    Revision 1.27  2001/09/16 17:08:54  jongfoster
266  *    Moving simple CGI functions from cgi.c to new file cgisimple.c
267  *
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.
273  *
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.
277  *
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.
285  *
286  *    Revision 1.23  2001/09/16 11:16:05  jongfoster
287  *    Better error handling in dispatch_cgi() and parse_cgi_parameters()
288  *
289  *    Revision 1.22  2001/09/16 11:00:10  jongfoster
290  *    New function alloc_http_response, for symmetry with free_http_response
291  *
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.
295  *
296  *    Revision 1.20  2001/09/13 23:40:36  jongfoster
297  *    (Cosmetic only) Indentation correction
298  *
299  *    Revision 1.19  2001/09/13 23:31:25  jongfoster
300  *    Moving image data to cgi.c rather than cgi.h.
301  *
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).
308  *
309  *    Revision 1.17  2001/08/05 15:57:38  oes
310  *    Adapted finish_http_response to new list_to_text
311  *
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".
316  *
317  *    Revision 1.15  2001/08/01 21:19:22  jongfoster
318  *    Moving file version information to a separate CGI page.
319  *
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()
323  *
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
329  *
330  *    Revision 1.12  2001/07/29 18:47:05  jongfoster
331  *    Adding missing #include "loadcfg.h"
332  *
333  *    Revision 1.11  2001/07/18 17:24:37  oes
334  *    Changed to conform to new pcrs interface
335  *
336  *    Revision 1.10  2001/07/13 13:53:13  oes
337  *    Removed all #ifdef PCRS and related code
338  *
339  *    Revision 1.9  2001/06/29 21:45:41  oes
340  *    Indentation, CRLF->LF, Tab-> Space
341  *
342  *    Revision 1.8  2001/06/29 13:21:46  oes
343  *    - Cosmetics: renamed and reordered functions, variables,
344  *      texts, improved comments  etc
345  *
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()
349  *
350  *    - Generators of content now call finish_http_response()
351  *      themselves, making jcc.c:chat() a little less
352  *      cluttered
353  *
354  *    - Removed obsolete "Pragma: no-cache" from our headers
355  *
356  *    - http_responses now know their head length
357  *
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
363  *
364  *    - Introduced default_exports() which generates a set of exports
365  *      common to all CGIs and other content generators
366  *
367  *    - Introduced convenience function map_block_killer()
368  *
369  *    - Introduced convenience function make_menu()
370  *
371  *    - Introduced CGI-like function error_response() which generates
372  *      the "No such domain" and "Connect failed" messages using the
373  *      CGI platform
374  *
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
379  *
380  *    - cgi_show_status:
381  *      - adapted to new CGI features
382  *      - no longer uses csp->init_proxy_args
383  *
384  *    - cgi_default:
385  *      - moved menu generation to make_menu()
386  *
387  *    - add_stats now writes single export map entries instead
388  *      of a fixed string
389  *
390  *    - Moved redirect_url() to filters.c
391  *
392  *    - Fixed mem leak in free_http_response(), map_block_killer(),
393  *
394  *    - Removed logentry from cancelled commit
395  *
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
399  *
400  *    Revision 1.6  2001/06/07 23:05:19  jongfoster
401  *    Removing code related to old forward and ACL files.
402  *
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++).
405  *
406  *    Revision 1.4  2001/06/04 10:41:52  swa
407  *    show version string of cgi.h and cgi.c
408  *
409  *    Revision 1.3  2001/06/03 19:12:16  oes
410  *    introduced new cgi handling
411  *
412  *    No revisions before 1.3
413  *
414  **********************************************************************/
415 \f
416
417 #include "config.h"
418
419 #include <stdio.h>
420 #include <sys/types.h>
421 #include <stdlib.h>
422 #include <ctype.h>
423 #include <string.h>
424 #include <limits.h>
425 #include <assert.h>
426
427 #ifdef _WIN32
428 #define snprintf _snprintf
429 #endif /* def _WIN32 */
430
431 #include "project.h"
432 #include "cgi.h"
433 #include "list.h"
434 #include "encode.h"
435 #include "ssplit.h"
436 #include "errlog.h"
437 #include "miscutil.h"
438 #include "cgisimple.h"
439 #ifdef FEATURE_CGI_EDIT_ACTIONS
440 #include "cgiedit.h"
441 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
442 #include "loadcfg.h"
443 /* loadcfg.h is for global_toggle_state only */
444 #ifdef FEATURE_PTHREAD
445 #include <pthread.h>
446 #include "jcc.h"
447 /* jcc.h is for mutex semaphore globals only */
448 #endif /* def FEATURE_PTHREAD */
449 const char cgi_h_rcs[] = CGI_H_VERSION;
450
451 /*
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!
455  */
456 static const struct cgi_dispatcher cgi_dispatchers[] = {
457    { "",
458          cgi_default,
459          "Privoxy main page",
460          TRUE },
461 #ifdef FEATURE_GRACEFUL_TERMINATION
462    { "die", 
463          cgi_die,  
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>",
466          FALSE }, 
467 #endif
468    { "show-status", 
469          cgi_show_status,  
470         "View & change the current configuration",
471          TRUE }, 
472    { "show-version", 
473          cgi_show_version,  
474          "View the source code version numbers",
475           TRUE }, 
476    { "show-request", 
477          cgi_show_request,  
478          "View the request headers.",
479          TRUE }, 
480    { "show-url-info",
481          cgi_show_url_info, 
482          "Look up which actions apply to a URL and why",
483          TRUE },
484 #ifdef FEATURE_CGI_EDIT_ACTIONS
485    { "toggle",
486          cgi_toggle, 
487          "Toggle Privoxy on or off",
488          FALSE },
489    { "edit-actions", /* Edit the actions list */
490          cgi_edit_actions, 
491          NULL, FALSE },
492    { "eaa", /* Shortcut for edit-actions-add-url-form */
493          cgi_edit_actions_add_url_form, 
494          NULL, FALSE },
495    { "eau", /* Shortcut for edit-actions-url-form */
496          cgi_edit_actions_url_form, 
497          NULL, FALSE },
498    { "ear", /* Shortcut for edit-actions-remove-url-form */
499          cgi_edit_actions_remove_url_form, 
500          NULL, FALSE },
501    { "eafu", /* Shortcut for edit-actions-for-url */
502          cgi_edit_actions_for_url, 
503          NULL, FALSE },
504    { "eas", /* Shortcut for edit-actions-submit */
505          cgi_edit_actions_submit, 
506          NULL, FALSE },
507    { "easa", /* Shortcut for edit-actions-section-add */
508          cgi_edit_actions_section_add, 
509          NULL, FALSE  },
510    { "easr", /* Shortcut for edit-actions-section-remove */
511          cgi_edit_actions_section_remove, 
512          NULL, FALSE  },
513    { "eass", /* Shortcut for edit-actions-section-swap */
514          cgi_edit_actions_section_swap, 
515          NULL, FALSE  },
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 */
553    { "robots.txt", 
554          cgi_robots_txt,  
555          NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ }, 
556    { "send-banner",
557          cgi_send_banner, 
558          NULL, TRUE /* Send a built-in image */ },
559    { "send-stylesheet",
560          cgi_send_stylesheet, 
561          NULL, TRUE /* Send templates/cgi-style.css */ },
562    { "t",
563          cgi_transparent_image, 
564          NULL, TRUE /* Send a transparent image (short name) */ },
565    { NULL, /* NULL Indicates end of list and default page */
566          cgi_error_404,
567          NULL, TRUE /* Unknown CGI page */ }
568 };
569
570
571 /*
572  * Bulit-in images for ad replacement
573  *
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)); }'
576  */
577
578 #ifdef FEATURE_NO_GIFS
579
580 /*
581  * Checkerboard pattern, as a PNG.
582  */
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";
591
592 /*
593  * 1x1 transparant PNG.
594  */
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";
605 #else
606
607 /*
608  * Checkerboard pattern, as a GIF.
609  */
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"
615    "\270\005\000\073";
616
617 /*
618  * 1x1 transparant GIF.
619  */
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;";
624 #endif
625
626 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
627 const size_t image_blank_length   = sizeof(image_blank_data) - 1;
628
629
630 static struct http_response cgi_error_memory_response[1];
631
632 static struct http_response *dispatch_known_cgi(struct client_state * csp,
633                                                 const char * path);
634 static struct map *parse_cgi_parameters(char *argstring);
635
636
637 /*********************************************************************
638  * 
639  * Function    :  dispatch_cgi
640  *
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.
647  *
648  * Parameters  :
649  *          1  :  csp = Current client state (buffers, headers, etc...)
650  *
651  * Returns     :  http_response if match, NULL if nonmatch or handler fail
652  *
653  *********************************************************************/
654 struct http_response *dispatch_cgi(struct client_state *csp)
655 {
656    const char *host = csp->http->host;
657    const char *path = csp->http->path;
658
659    /*
660     * Should we intercept ?
661     */
662
663    /* Note: "example.com" and "example.com." are equivalent hostnames. */
664
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] == '/') )
669    {
670       /* ..then the path will all be for us.  Remove leading '/' */
671       path++;
672    }
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))) )
677    {
678       /* take everything following CGI_SITE_2_PATH */
679       path += strlen(CGI_SITE_2_PATH);
680       if (*path == '/')
681       {
682          /* skip the forward slash after CGI_SITE_2_PATH */
683          path++;
684       }
685       else if (*path != '\0')
686       {
687          /*
688           * wierdness: URL is /configXXX, where XXX is some string
689           * Do *NOT* intercept.
690           */
691          return NULL;
692       }
693    }
694    else
695    {
696       /* Not a CGI */
697       return NULL;
698    }
699
700    /* 
701     * This is a CGI call.
702     */
703
704    return dispatch_known_cgi(csp, path);
705 }
706
707
708 /*********************************************************************
709  *
710  * Function    :  grep_cgi_referrer
711  *
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
715  *                in Privoxy 3.1.
716  *
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!
720  *
721  * Parameters  :
722  *          1  :  csp = Current client state (buffers, headers, etc...)
723  *
724  * Returns     :  pointer to value (no copy!), or NULL if none found.
725  *
726  *********************************************************************/
727 char *grep_cgi_referrer(struct client_state *csp)
728 {
729    struct list_entry *p;
730
731    for (p = csp->headers->first; p != NULL; p = p->next)
732    {
733       if (p->str == NULL) continue;
734       if (strncmpic(p->str, "Referer: ", 9) == 0)
735       {
736          return ((p->str) + 9);
737       }
738    }
739    return NULL;
740
741 }
742
743
744 /*********************************************************************
745  * 
746  * Function    :  dispatch_known_cgi
747  *
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
753  *                handler function.
754  *
755  * Parameters  :
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 "/".
759  *
760  * Returns     :  http_response, or NULL on handler failure or out of
761  *                memory.
762  *
763  *********************************************************************/
764 static struct http_response *dispatch_known_cgi(struct client_state * csp,
765                                                 const char * path)
766 {
767    const struct cgi_dispatcher *d;
768    struct map *param_list;
769    struct http_response *rsp;
770    char *query_args_start;
771    char *path_copy;
772    char *referrer;
773    jb_err err;
774
775    if (NULL == (path_copy = strdup(path)))
776    {
777       return cgi_error_memory();
778    }
779
780    query_args_start = path_copy;
781    while (*query_args_start && *query_args_start != '?')
782    {
783       query_args_start++;
784    }
785    if (*query_args_start == '?')
786    {
787       *query_args_start++ = '\0';
788    }
789
790    if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
791    {
792       free(path_copy);
793       return cgi_error_memory();
794    }
795
796    /*
797     * At this point:
798     * path_copy        = CGI call name
799     * param_list       = CGI params, as map
800     */
801
802    /* Get mem for response or fail*/
803    if (NULL == (rsp = alloc_http_response()))
804    {
805       free(path_copy);
806       free_map(param_list);
807       return cgi_error_memory();
808    }
809
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); 
813
814    /* 
815     * Find and start the right CGI function
816     */
817    d = cgi_dispatchers;
818    for (;;)
819    {
820       if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
821       {
822          /*
823           * If the called CGI is either harmless, or not referred
824           * from an untrusted source, start it.
825           */
826          if (d->harmless
827              || (NULL == (referrer = grep_cgi_referrer(csp)))
828              || (0 == strncmp(referrer, "http://config.privoxy.org/", 26))
829              )
830          {
831             err = (d->handler)(csp, rsp, param_list);
832          }
833          else
834          {
835             /*
836              * Else, modify toggle calls so that they only display
837              * the status, and deny all other calls.
838              */
839             if (0 == strcmp(path_copy, "toggle"))
840             {
841                unmap(param_list, "set");
842                err = (d->handler)(csp, rsp, param_list);
843             }
844             else
845             {
846                err = cgi_error_disabled(csp, rsp);
847             }
848          }
849
850          free(path_copy);
851          free_map(param_list);
852
853          if (err == JB_ERR_CGI_PARAMS)
854          {
855             err = cgi_error_bad_param(csp, rsp);
856          }
857          if (err && (err != JB_ERR_MEMORY))
858          {
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);
862          }
863          if (!err)
864          {
865             /* It worked */
866             return finish_http_response(rsp);
867          }
868          else
869          {
870             /* Error in handler, probably out-of-memory */
871             free_http_response(rsp);
872             return cgi_error_memory();
873          }
874       }
875       d++;
876    }
877 }
878    
879         
880 /*********************************************************************
881  *
882  * Function    :  parse_cgi_parameters
883  *
884  * Description :  Parse a URL-encoded argument string into name/value
885  *                pairs and store them in a struct map list.
886  *
887  * Parameters  :
888  *          1  :  argstring = string to be parsed.  Will be trashed.
889  *
890  * Returns     :  pointer to param list, or NULL if out of memory.
891  *
892  *********************************************************************/
893 static struct map *parse_cgi_parameters(char *argstring)
894 {
895    char *p;
896    char *vector[BUFFER_SIZE];
897    int pairs, i;
898    struct map *cgi_params;
899
900    if (NULL == (cgi_params = new_map()))
901    {
902       return NULL;
903    }
904
905    /* 
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:
909     */
910    if (NULL != (p = strchr(argstring, '#')))
911    {
912       *p = '\0';
913    }
914
915    pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
916
917    for (i = 0; i < pairs; i++)
918    {
919       if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
920       {
921          *p = '\0';
922          if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
923          {
924             free_map(cgi_params);
925             return NULL;
926          }
927       }
928    }
929
930    return cgi_params;
931
932 }
933
934
935 /*********************************************************************
936  *
937  * Function    :  get_char_param
938  *
939  * Description :  Get a single-character parameter passed to a CGI
940  *                function.
941  *
942  * Parameters  :
943  *          1  :  parameters = map of cgi parameters
944  *          2  :  param_name = The name of the parameter to read
945  *
946  * Returns     :  Uppercase character on success, '\0' on error.
947  *
948  *********************************************************************/
949 char get_char_param(const struct map *parameters,
950                     const char *param_name)
951 {
952    char ch;
953
954    assert(parameters);
955    assert(param_name);
956
957    ch = *(lookup(parameters, param_name));
958    if ((ch >= 'a') && (ch <= 'z'))
959    {
960       ch = ch - 'a' + 'A';
961    }
962
963    return ch;
964 }
965
966
967 /*********************************************************************
968  *
969  * Function    :  get_string_param
970  *
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.
975  *
976  * Parameters  :
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.
982  *
983  * Returns     :  JB_ERR_OK         on success, or if the paramater
984  *                                  was not specified.
985  *                JB_ERR_MEMORY     on out-of-memory.
986  *                JB_ERR_CGI_PARAMS if the paramater is not valid.
987  *
988  *********************************************************************/
989 jb_err get_string_param(const struct map *parameters,
990                         const char *param_name,
991                         const char **pparam)
992 {
993    const char *param;
994    const char *s;
995    char ch;
996
997    assert(parameters);
998    assert(param_name);
999    assert(pparam);
1000
1001    *pparam = NULL;
1002
1003    param = lookup(parameters, param_name);
1004    if (!*param)
1005    {
1006       return JB_ERR_OK;
1007    }
1008
1009    if (strlen(param) >= CGI_PARAM_LEN_MAX)
1010    {
1011       /*
1012        * Too long.
1013        *
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.
1017        */
1018       return JB_ERR_CGI_PARAMS;
1019    }
1020
1021    /* Check every character to see if it's legal */
1022    s = param;
1023    while ((ch = *s++) != '\0')
1024    {
1025       if ( ((unsigned char)ch < (unsigned char)' ')
1026         || (ch == '}') )
1027       {
1028          /* Probable hack attempt, or user accidentally used '}'. */
1029          return JB_ERR_CGI_PARAMS;
1030       }
1031    }
1032
1033    /* Success */
1034    *pparam = param;
1035
1036    return JB_ERR_OK;
1037 }
1038
1039
1040 /*********************************************************************
1041  *
1042  * Function    :  get_number_param
1043  *
1044  * Description :  Get a non-negative integer from the parameters
1045  *                passed to a CGI function.
1046  *
1047  * Parameters  :
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.
1053  *
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
1057  *                                  or is not valid.
1058  *
1059  *********************************************************************/
1060 jb_err get_number_param(struct client_state *csp,
1061                         const struct map *parameters,
1062                         char *name,
1063                         unsigned *pvalue)
1064 {
1065    const char *param;
1066    char ch;
1067    unsigned value;
1068
1069    assert(csp);
1070    assert(parameters);
1071    assert(name);
1072    assert(pvalue);
1073
1074    *pvalue = 0; 
1075
1076    param = lookup(parameters, name);
1077    if (!*param)
1078    {
1079       return JB_ERR_CGI_PARAMS;
1080    }
1081
1082    /* We don't use atoi because I want to check this carefully... */
1083
1084    value = 0;
1085    while ((ch = *param++) != '\0')
1086    {
1087       if ((ch < '0') || (ch > '9'))
1088       {
1089          return JB_ERR_CGI_PARAMS;
1090       }
1091
1092       ch -= '0';
1093
1094       /* Note:
1095        *
1096        * <limits.h> defines UINT_MAX
1097        *
1098        * (UINT_MAX - ch) / 10 is the largest number that
1099        *     can be safely multiplied by 10 then have ch added.
1100        */
1101       if (value > ((UINT_MAX - (unsigned)ch) / 10U))
1102       {
1103          return JB_ERR_CGI_PARAMS;
1104       }
1105
1106       value = value * 10 + ch;
1107    }
1108
1109    /* Success */
1110    *pvalue = value;
1111
1112    return JB_ERR_OK;
1113
1114 }
1115
1116
1117 /*********************************************************************
1118  *
1119  * Function    :  error_response
1120  *
1121  * Description :  returns an http_response that explains the reason
1122  *                why a request failed.
1123  *
1124  * Parameters  :
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
1128  *
1129  * Returns     :  A http_response.  If we run out of memory, this
1130  *                will be cgi_error_memory().
1131  *
1132  *********************************************************************/
1133 struct http_response *error_response(struct client_state *csp,
1134                                      const char *templatename,
1135                                      int sys_err)
1136 {
1137    jb_err err;
1138    struct http_response *rsp;
1139    struct map * exports = default_exports(csp, NULL);
1140    if (exports == NULL)
1141    {
1142       return cgi_error_memory();
1143    }
1144
1145    if (NULL == (rsp = alloc_http_response()))
1146    {
1147       free_map(exports);
1148       return cgi_error_memory();
1149    }
1150
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); 
1156    if (!err)
1157    {
1158      err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1159      if (err)
1160      {
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);
1163      }
1164    }
1165
1166
1167    if (err)
1168    {
1169       free_map(exports);
1170       free_http_response(rsp);
1171       return cgi_error_memory();
1172    }
1173
1174    if (!strcmp(templatename, "no-such-domain"))
1175    {
1176       rsp->status = strdup("404 No such domain");
1177       if (rsp->status == NULL)
1178       {
1179          free_map(exports);
1180          free_http_response(rsp);
1181          return cgi_error_memory();
1182       }
1183    }
1184    else if (!strcmp(templatename, "connect-failed"))
1185    {
1186       rsp->status = strdup("503 Connect failed");
1187       if (rsp->status == NULL)
1188       {
1189          free_map(exports);
1190          free_http_response(rsp);
1191          return cgi_error_memory();
1192       }
1193    }
1194
1195    err = template_fill_for_cgi(csp, templatename, exports, rsp);
1196    if (err)
1197    {
1198       free_http_response(rsp);
1199       return cgi_error_memory();
1200    }
1201
1202    return finish_http_response(rsp);
1203 }
1204
1205
1206 /*********************************************************************
1207  *
1208  * Function    :  cgi_init_error_messages
1209  *
1210  * Description :  Call at the start of the program to initialize
1211  *                the error message used by cgi_error_memory().
1212  *
1213  * Parameters  :  N/A
1214  *
1215  * Returns     :  N/A
1216  *
1217  *********************************************************************/
1218 void cgi_init_error_messages(void)
1219 {
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"
1224       "\r\n";
1225    cgi_error_memory_response->body =
1226       "<html>\r\n"
1227       "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1228       "<body>\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"
1232       "</body>\r\n"
1233       "</html>\r\n";
1234
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);
1239 }
1240
1241
1242 /*********************************************************************
1243  *
1244  * Function    :  cgi_error_memory
1245  *
1246  * Description :  Called if a CGI function runs out of memory.
1247  *                Returns a statically-allocated error response.
1248  *
1249  * Parameters  :  N/A
1250  *
1251  * Returns     :  http_response data structure for output.  This is
1252  *                statically allocated, for obvious reasons.
1253  *
1254  *********************************************************************/
1255 struct http_response *cgi_error_memory(void)
1256 {
1257    /* assert that it's been initialized. */
1258    assert(cgi_error_memory_response->head);
1259
1260    return cgi_error_memory_response;
1261 }
1262
1263
1264 /*********************************************************************
1265  *
1266  * Function    :  cgi_error_no_template
1267  *
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 
1271  *                parameters.
1272  *
1273  * Parameters  :
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
1277  *                                be loaded.
1278  *
1279  * Returns     :  JB_ERR_OK on success
1280  *                JB_ERR_MEMORY on out-of-memory error.  
1281  *
1282  *********************************************************************/
1283 jb_err cgi_error_no_template(struct client_state *csp,
1284                              struct http_response *rsp,
1285                              const char *template_name)
1286 {
1287    static const char status[] =
1288       "500 Internal Privoxy Error";
1289    static const char body_prefix[] =
1290       "<html>\r\n"
1291       "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1292       "<body>\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"
1304 #ifndef _WIN32
1305       ", or <code>/etc/privoxy/</code>"
1306 #endif /* ndef _WIN32 */
1307       ").</p>\r\n"
1308       "</body>\r\n"
1309       "</html>\r\n";
1310
1311    assert(csp);
1312    assert(rsp);
1313    assert(template_name);
1314
1315    /* Reset rsp, if needed */
1316    freez(rsp->status);
1317    freez(rsp->head);
1318    freez(rsp->body);
1319    rsp->content_length = 0;
1320    rsp->head_length = 0;
1321    rsp->is_static = 0;
1322
1323    rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1324    if (rsp->body == NULL)
1325    {
1326       return JB_ERR_MEMORY;
1327    }
1328    strcpy(rsp->body, body_prefix);
1329    strcat(rsp->body, template_name);
1330    strcat(rsp->body, body_suffix);
1331
1332    rsp->status = strdup(status);
1333    if (rsp->body == NULL)
1334    {
1335       return JB_ERR_MEMORY;
1336    }
1337
1338    return JB_ERR_OK;
1339 }
1340
1341
1342 /*********************************************************************
1343  *
1344  * Function    :  cgi_error_unknown
1345  *
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
1352  *                that way.
1353  *
1354  *                Note this is not a true CGI, it takes an error
1355  *                code rather than a map of parameters.
1356  *
1357  * 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.
1361  *
1362  * Returns     :  JB_ERR_OK on success
1363  *                JB_ERR_MEMORY on out-of-memory error.  
1364  *
1365  *********************************************************************/
1366 jb_err cgi_error_unknown(struct client_state *csp,
1367                          struct http_response *rsp,
1368                          jb_err error_to_report)
1369 {
1370    static const char status[] =
1371       "500 Internal Privoxy Error";
1372    static const char body_prefix[] =
1373       "<html>\r\n"
1374       "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1375       "<body>\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[] =
1380       "</b></p>\r\n"
1381       "<p>Please "
1382       "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1383       "file a bug report</a>.</p>\r\n"
1384       "</body>\r\n"
1385       "</html>\r\n";
1386    char errnumbuf[30];
1387    assert(csp);
1388    assert(rsp);
1389
1390    /* Reset rsp, if needed */
1391    freez(rsp->status);
1392    freez(rsp->head);
1393    freez(rsp->body);
1394    rsp->content_length = 0;
1395    rsp->head_length = 0;
1396    rsp->is_static = 0;
1397
1398    sprintf(errnumbuf, "%d", error_to_report);
1399
1400    rsp->body = malloc(strlen(body_prefix) + strlen(errnumbuf) + strlen(body_suffix) + 1);
1401    if (rsp->body == NULL)
1402    {
1403       return JB_ERR_MEMORY;
1404    }
1405    strcpy(rsp->body, body_prefix);
1406    strcat(rsp->body, errnumbuf);
1407    strcat(rsp->body, body_suffix);
1408
1409    rsp->status = strdup(status);
1410    if (rsp->body == NULL)
1411    {
1412       return JB_ERR_MEMORY;
1413    }
1414
1415    return JB_ERR_OK;
1416 }
1417
1418
1419 /*********************************************************************
1420  *
1421  * Function    :  cgi_error_bad_param
1422  *
1423  * Description :  CGI function that is called if the parameters
1424  *                (query string) for a CGI were wrong.
1425  *               
1426  * Parameters  :
1427  *          1  :  csp = Current client state (buffers, headers, etc...)
1428  *          2  :  rsp = http_response data structure for output
1429  *
1430  * CGI Parameters : none
1431  *
1432  * Returns     :  JB_ERR_OK on success
1433  *                JB_ERR_MEMORY on out-of-memory error.  
1434  *
1435  *********************************************************************/
1436 jb_err cgi_error_bad_param(struct client_state *csp,
1437                            struct http_response *rsp)
1438 {
1439    struct map *exports;
1440
1441    assert(csp);
1442    assert(rsp);
1443
1444    if (NULL == (exports = default_exports(csp, NULL)))
1445    {
1446       return JB_ERR_MEMORY;
1447    }
1448
1449    return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1450 }
1451
1452
1453 /*********************************************************************
1454  *
1455  * Function    :  add_help_link
1456  *
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).
1462  *
1463  *                FIXME: I currently only work for actions, and would
1464  *                       like to be generalized for other topics.
1465  *
1466  * Parameters  :  
1467  *          1  :  item = item (will NOT be free()d.) 
1468  *                       It is assumed to be HTML-safe.
1469  *          2  :  config = The current configuration.
1470  *
1471  * Returns     :  String with item embedded in link, or NULL on
1472  *                out-of-memory
1473  *
1474  *********************************************************************/
1475 char *add_help_link(const char *item,
1476                     struct configuration_spec *config)
1477 {
1478    char *result;
1479
1480    if (!item) return NULL;
1481
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> ");
1489
1490    return result;
1491 }
1492
1493
1494 /*********************************************************************
1495  *
1496  * Function    :  get_http_time
1497  *
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"
1501  *
1502  * Parameters  :  
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.
1507  *
1508  * Returns     :  N/A
1509  *
1510  *********************************************************************/
1511 void get_http_time(int time_offset, char *buf)
1512 {
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" };
1518
1519    struct tm *t;
1520    time_t current_time;
1521 #ifdef HAVE_GMTIME_R
1522    /*
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.
1527     */
1528    struct tm dummy; 
1529 #endif
1530
1531    assert(buf);
1532
1533    time(&current_time); /* get current time */
1534
1535    current_time += time_offset;
1536
1537    /* get and save the gmt */
1538    {
1539 #ifdef OSX_DARWIN
1540       pthread_mutex_lock(&gmtime_mutex);
1541       t = gmtime(&current_time);
1542       pthread_mutex_unlock(&gmtime_mutex);
1543 #elif HAVE_GMTIME_R
1544       t = gmtime_r(&current_time, &dummy);
1545 #else
1546       t = gmtime(&current_time);
1547 #endif
1548    }
1549
1550    /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1551    snprintf(buf, 30,
1552       "%s, %02d %s %4d %02d:%02d:%02d GMT",
1553       day_names[t->tm_wday],
1554       t->tm_mday,
1555       month_names[t->tm_mon],
1556       t->tm_year + 1900,
1557       t->tm_hour,
1558       t->tm_min,
1559       t->tm_sec
1560       );
1561
1562 }
1563
1564
1565 /*********************************************************************
1566  *
1567  * Function    :  finish_http_response
1568  *
1569  * Description :  Fill in the missing headers in an http response,
1570  *                and flatten the headers to an http head.
1571  *
1572  * Parameters  :
1573  *          1  :  rsp = pointer to http_response to be processed
1574  *
1575  * Returns     :  A http_response, usually the rsp parameter.
1576  *                On error, free()s rsp and returns cgi_error_memory()
1577  *
1578  *********************************************************************/
1579 struct http_response *finish_http_response(struct http_response *rsp)
1580 {
1581    char buf[BUFFER_SIZE];
1582    jb_err err;
1583
1584    /* Special case - do NOT change this statically allocated response,
1585     * which is ready for output anyway.
1586     */
1587    if (rsp == cgi_error_memory_response)
1588    {
1589       return rsp;
1590    }
1591
1592    /* 
1593     * Fill in the HTTP Status
1594     */
1595    sprintf(buf, "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1596    err = enlist_first(rsp->headers, buf);
1597
1598    /* 
1599     * Set the Content-Length
1600     */
1601    if (rsp->content_length == 0)
1602    {
1603       rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1604    }
1605    if (!err)
1606    {
1607       sprintf(buf, "Content-Length: %d", (int)rsp->content_length);
1608       err = enlist(rsp->headers, buf);
1609    }
1610
1611    /* 
1612     * Fill in the default headers:
1613     *
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.
1619     * 
1620     * See http://www.w3.org/Protocols/rfc2068/rfc2068
1621     */
1622    if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1623
1624    if (rsp->is_static)
1625    {
1626       /*
1627        * Set Expires to about 10 min into the future so it'll get reloaded
1628        * occasionally, e.g. if Privoxy gets upgraded.
1629        */
1630
1631       if (!err)
1632       {
1633          get_http_time(0, buf);
1634          err = enlist_unique_header(rsp->headers, "Date", buf);
1635       }
1636
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");
1639
1640       if (!err)
1641       {
1642          get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
1643          err = enlist_unique_header(rsp->headers, "Expires", buf);
1644       }
1645    }
1646    else
1647    {
1648       /*
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.
1652        */
1653       if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
1654
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);
1659    }
1660
1661
1662    /* 
1663     * Write the head
1664     */
1665    if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
1666    {
1667       free_http_response(rsp);
1668       return cgi_error_memory();
1669    }
1670    rsp->head_length = strlen(rsp->head);
1671
1672    return rsp;
1673
1674 }
1675
1676
1677 /*********************************************************************
1678  *
1679  * Function    :  alloc_http_response
1680  *
1681  * Description :  Allocates a new http_response structure.
1682  *
1683  * Parameters  :  N/A
1684  *
1685  * Returns     :  pointer to a new http_response, or NULL.
1686  *
1687  *********************************************************************/
1688 struct http_response *alloc_http_response(void)
1689 {
1690    return (struct http_response *) zalloc(sizeof(struct http_response));
1691
1692 }
1693
1694
1695 /*********************************************************************
1696  *
1697  * Function    :  free_http_response
1698  *
1699  * Description :  Free the memory occupied by an http_response
1700  *                and its depandant structures.
1701  *
1702  * Parameters  :
1703  *          1  :  rsp = pointer to http_response to be freed
1704  *
1705  * Returns     :  N/A
1706  *
1707  *********************************************************************/
1708 void free_http_response(struct http_response *rsp)
1709 {
1710    /*
1711     * Must special case cgi_error_memory_response, which is never freed.
1712     */
1713    if (rsp && (rsp != cgi_error_memory_response))
1714    {
1715       freez(rsp->status);
1716       freez(rsp->head);
1717       freez(rsp->body);
1718       destroy_list(rsp->headers);
1719       free(rsp);
1720    }
1721
1722 }
1723
1724
1725 /*********************************************************************
1726  *
1727  * Function    :  template_load
1728  *
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
1732  *                a depth of 1.
1733  *
1734  * Parameters  :
1735  *          1  :  csp = Current client state (buffers, headers, etc...)
1736  *          2  :  template_ptr = Destination for pointer to loaded
1737  *                               template text.
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
1741  *
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
1745  *
1746  *********************************************************************/
1747 jb_err template_load(struct client_state *csp, char **template_ptr, 
1748                      const char *templatename, int recursive)
1749 {
1750    jb_err err;
1751    char *templates_dir_path;
1752    char *full_path;
1753    char *file_buffer;
1754    char *included_module;
1755    const char *p;
1756    FILE *fp;
1757    char buf[BUFFER_SIZE];
1758
1759    assert(csp);
1760    assert(template_ptr);
1761    assert(templatename);
1762
1763    *template_ptr = NULL;
1764
1765    /* Validate template name.  Paranoia. */
1766    for (p = templatename; *p != 0; p++)
1767    {
1768       if ( ((*p < 'a') || (*p > 'z'))
1769         && ((*p < 'A') || (*p > 'Z'))
1770         && ((*p < '0') || (*p > '9'))
1771         && (*p != '-')
1772         && (*p != '.'))
1773       {
1774          /* Illegal character */
1775          return JB_ERR_FILE;
1776       }
1777    }
1778
1779    /* Generate full path */
1780
1781    templates_dir_path = make_path(csp->config->confdir, "templates");
1782    if (templates_dir_path == NULL)
1783    {
1784       return JB_ERR_MEMORY;
1785    }
1786
1787    full_path = make_path(templates_dir_path, templatename);
1788    free(templates_dir_path);
1789    if (full_path == NULL)
1790    {
1791       return JB_ERR_MEMORY;
1792    }
1793
1794    /* Allocate buffer */
1795
1796    file_buffer = strdup("");
1797    if (file_buffer == NULL)
1798    {
1799       free(full_path);
1800       return JB_ERR_MEMORY;
1801    }
1802
1803    /* Open template file */
1804
1805    if (NULL == (fp = fopen(full_path, "r")))
1806    {
1807       log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
1808       free(full_path);
1809       free(file_buffer);
1810       return JB_ERR_FILE;
1811    }
1812    free(full_path);
1813
1814    /* 
1815     * Read the file, ignoring comments, and honoring #include
1816     * statements, unless we're already called recursively.
1817     *
1818     * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
1819     *        This is unlikely in practise.
1820     */
1821    while (fgets(buf, BUFFER_SIZE, fp))
1822    {
1823       if (!recursive && !strncmp(buf, "#include ", 9))
1824       {
1825          if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
1826          {
1827             free(file_buffer);
1828             fclose(fp);
1829             return err;
1830          }
1831
1832          if (string_join(&file_buffer, included_module))
1833          {
1834             fclose(fp);
1835             return JB_ERR_MEMORY;
1836          }
1837
1838          continue;
1839       }
1840
1841       /* skip lines starting with '#' */
1842       if (*buf == '#')
1843       {
1844          continue;
1845       }
1846
1847       if (string_append(&file_buffer, buf))
1848       {
1849          fclose(fp);
1850          return JB_ERR_MEMORY;
1851       }
1852    }
1853    fclose(fp);
1854
1855    *template_ptr = file_buffer;
1856
1857    return JB_ERR_OK;
1858 }
1859
1860
1861 /*********************************************************************
1862  *
1863  * Function    :  template_fill
1864  *
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.
1868  *
1869  *                Note that a leading '$' charachter in the export map's
1870  *                values will be stripped and toggle on backreference
1871  *                interpretation.
1872  *
1873  * Parameters  :
1874  *          1  :  template_ptr = IN: Template to be filled out.
1875  *                                   Will be free()d.
1876  *                               OUT: Filled out template.
1877  *                                    Caller must free().
1878  *          2  :  exports = map with fill in symbol -> name pairs
1879  *
1880  * Returns     :  JB_ERR_OK on success
1881  *                JB_ERR_MEMORY on out-of-memory error
1882  *
1883  *********************************************************************/
1884 jb_err template_fill(char **template_ptr, const struct map *exports)
1885 {
1886    struct map_entry *m;
1887    pcrs_job *job;
1888    char buf[BUFFER_SIZE];
1889    char *tmp_out_buffer;
1890    char *file_buffer;
1891    size_t  size;
1892    int error;
1893    const char *flags;
1894
1895    assert(template_ptr);
1896    assert(*template_ptr);
1897    assert(exports);
1898
1899    file_buffer = *template_ptr;
1900    size = strlen(file_buffer) + 1;
1901
1902    /* 
1903     * Assemble pcrs joblist from exports map
1904     */
1905    for (m = exports->first; m != NULL; m = m->next)
1906    {
1907       if (*m->name == '$')
1908       {
1909          /*
1910           * First character of name is '$', so remove this flag
1911           * character and allow backreferences ($1 etc) in the
1912           * "replace with" text.
1913           */
1914          snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
1915          flags = "sigU";
1916       }
1917       else
1918       {
1919          /*
1920           * Treat the "replace with" text as a literal string - 
1921           * no quoting needed, no backreferences allowed.
1922           * ("Trivial" ['T'] flag).
1923           */
1924          flags = "sigTU";
1925
1926          /* Enclose name in @@ */
1927          snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
1928       }
1929
1930
1931       log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
1932
1933       /* Make and run job. */
1934       job = pcrs_compile(buf, m->value, flags,  &error);
1935       if (job == NULL) 
1936       {
1937          if (error == PCRS_ERR_NOMEM)
1938          {
1939             free(file_buffer);
1940             *template_ptr = NULL;
1941             return JB_ERR_MEMORY;
1942          }
1943          else
1944          {
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 */
1947          }
1948       }
1949       else
1950       {
1951          pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
1952          free(file_buffer);
1953          pcrs_free_job(job);
1954          if (NULL == tmp_out_buffer)
1955          {
1956             *template_ptr = NULL;
1957             return JB_ERR_MEMORY;
1958          }
1959          file_buffer = tmp_out_buffer;
1960       }
1961    }
1962
1963    /*
1964     * Return
1965     */
1966    *template_ptr = file_buffer;
1967    return JB_ERR_OK;
1968 }
1969
1970
1971 /*********************************************************************
1972  *
1973  * Function    :  template_fill_for_cgi
1974  *
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.
1979  *
1980  * Parameters  :
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.
1986  *
1987  * Returns     :  JB_ERR_OK on success
1988  *                JB_ERR_MEMORY on out-of-memory error
1989  *
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)
1995 {
1996    jb_err err;
1997    
1998    assert(csp);
1999    assert(templatename);
2000    assert(exports);
2001    assert(rsp);
2002
2003    err = template_load(csp, &rsp->body, templatename, 0);
2004    if (err == JB_ERR_FILE)
2005    {
2006       free_map(exports);
2007       return cgi_error_no_template(csp, rsp, templatename);
2008    }
2009    else if (err)
2010    {
2011       free_map(exports);
2012       return err; /* JB_ERR_MEMORY */
2013    }
2014    err = template_fill(&rsp->body, exports);
2015    free_map(exports);
2016    return err;
2017 }
2018
2019
2020 /*********************************************************************
2021  *
2022  * Function    :  default_exports
2023  *
2024  * Description :  returns a struct map list that contains exports
2025  *                which are common to all CGI functions.
2026  *
2027  * Parameters  :
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
2031  *                         NULL.
2032  * Returns     :  NULL if no memory, else a new map.  Caller frees.
2033  *
2034  *********************************************************************/
2035 struct map *default_exports(const struct client_state *csp, const char *caller)
2036 {
2037    char buf[20];
2038    jb_err err;
2039    struct map * exports;
2040    int local_help_exists = 0;
2041
2042    assert(csp);
2043
2044    exports = new_map();
2045    if (exports == NULL)
2046    {
2047       return NULL;
2048    }
2049
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);
2061 #endif
2062
2063    snprintf(buf, 20, "%d", csp->config->hport);
2064    if (!err) err = map(exports, "my-port", 1, buf, 1);
2065
2066    if(!strcmp(CODE_STATUS, "stable"))
2067    {
2068       if (!err) err = map_block_killer(exports, "unstable");
2069    }
2070
2071    if (csp->config->admin_address != NULL)
2072    {
2073       if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2074       local_help_exists = 1;
2075    }
2076    else
2077    {
2078       if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2079    }
2080
2081    if (csp->config->proxy_info_url != NULL)
2082    {
2083       if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2084       local_help_exists = 1;
2085    }
2086    else
2087    {
2088       if (!err) err = map_block_killer(exports, "have-proxy-info");
2089    }
2090
2091    if (local_help_exists == 0)
2092    {
2093       if (!err) err = map_block_killer(exports, "have-help-info");
2094    }
2095
2096    if (err)
2097    {
2098       free_map(exports);
2099       return NULL;
2100    }
2101
2102    return exports;
2103 }
2104
2105
2106 /*********************************************************************
2107  *
2108  * Function    :  map_block_killer
2109  *
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
2114  *                export list.
2115  *
2116  * Parameters  :  
2117  *          1  :  exports = map to extend
2118  *          2  :  name = name of conditional block
2119  *
2120  * Returns     :  JB_ERR_OK on success
2121  *                JB_ERR_MEMORY on out-of-memory error.  
2122  *
2123  *********************************************************************/
2124 jb_err map_block_killer(struct map *exports, const char *name)
2125 {
2126    char buf[1000]; /* Will do, since the names are hardwired */
2127
2128    assert(exports);
2129    assert(name);
2130    assert(strlen(name) < 490);
2131
2132    snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
2133    return map(exports, buf, 1, "", 1);
2134 }
2135
2136
2137 /*********************************************************************
2138  *
2139  * Function    :  map_block_keep
2140  *
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@"
2144  *
2145  * Parameters  :  
2146  *          1  :  exports = map to extend
2147  *          2  :  name = name of conditional block
2148  *
2149  * Returns     :  JB_ERR_OK on success
2150  *                JB_ERR_MEMORY on out-of-memory error.  
2151  *
2152  *********************************************************************/
2153 jb_err map_block_keep(struct map *exports, const char *name)
2154 {
2155    jb_err err;
2156    char buf[500]; /* Will do, since the names are hardwired */
2157
2158    assert(exports);
2159    assert(name);
2160    assert(strlen(name) < 490);
2161
2162    snprintf(buf, 500, "if-%s-start", name);
2163    err = map(exports, buf, 1, "", 1);
2164
2165    if (err)
2166    {
2167       return err;
2168    }
2169
2170    snprintf(buf, 500, "if-%s-end", name);
2171    return map(exports, buf, 1, "", 1);
2172 }
2173
2174
2175 /*********************************************************************
2176  *
2177  * Function    :  map_conditional
2178  *
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:
2182  *                @if-<name>-then@
2183  *                   True text
2184  *                @else-not-<name>@
2185  *                   False text
2186  *                @endif-<name>@
2187  *
2188  *                The control structure and one of the alternatives
2189  *                will be hidden.
2190  *
2191  * Parameters  :  
2192  *          1  :  exports = map to extend
2193  *          2  :  name = name of conditional block
2194  *          3  :  choose_first = nonzero for first, zero for second.
2195  *
2196  * Returns     :  JB_ERR_OK on success
2197  *                JB_ERR_MEMORY on out-of-memory error.  
2198  *
2199  *********************************************************************/
2200 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2201 {
2202    char buf[1000]; /* Will do, since the names are hardwired */
2203    jb_err err;
2204
2205    assert(exports);
2206    assert(name);
2207    assert(strlen(name) < 480);
2208
2209    snprintf(buf, 1000, (choose_first
2210       ? "else-not-%s@.*@endif-%s"
2211       : "if-%s-then@.*@else-not-%s"),
2212       name, name);
2213
2214    err = map(exports, buf, 1, "", 1);
2215    if (err)
2216    {
2217       return err;
2218    }
2219
2220    snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
2221    return map(exports, buf, 1, "", 1);
2222 }
2223
2224
2225 /*********************************************************************
2226  *
2227  * Function    :  make_menu
2228  *
2229  * Description :  Returns an HTML-formatted menu of the available 
2230  *                unhidden CGIs, excluding the one given in <self>
2231  *
2232  * Parameters  :  self = name of CGI to leave out, can be NULL for
2233  *                complete listing.
2234  *
2235  * Returns     :  menu string, or NULL on out-of-memory error.
2236  *
2237  *********************************************************************/
2238 char *make_menu(const char *self)
2239 {
2240    const struct cgi_dispatcher *d;
2241    char *result = strdup("");
2242
2243    if (self == NULL)
2244    {
2245       self = "NO-SUCH-CGI!";
2246    }
2247
2248    /* List available unhidden CGI's and export as "other-cgis" */
2249    for (d = cgi_dispatchers; d->name; d++)
2250    {
2251       if (d->description && strcmp(d->name, self))
2252       {
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>");
2258       }
2259    }
2260
2261    return result;
2262 }
2263
2264
2265 /*********************************************************************
2266  *
2267  * Function    :  dump_map
2268  *
2269  * Description :  HTML-dump a map for debugging (as table)
2270  *
2271  * Parameters  :
2272  *          1  :  the_map = map to dump
2273  *
2274  * Returns     :  string with HTML
2275  *
2276  *********************************************************************/
2277 char *dump_map(const struct map *the_map)
2278 {
2279    struct map_entry *cur_entry;
2280    char *ret = strdup("");
2281
2282    string_append(&ret, "<table>\n");
2283
2284    for (cur_entry = the_map->first;
2285         (cur_entry != NULL) && (ret != NULL);
2286         cur_entry = cur_entry->next)
2287    {
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");
2293    }
2294
2295    string_append(&ret, "</table>\n");
2296    return ret;
2297 }
2298
2299
2300 /*
2301   Local Variables:
2302   tab-width: 3
2303   end:
2304 */