- Add HEAD support to finish_http_response.
[privoxy.git] / cgi.c
1 const char cgi_rcs[] = "$Id: cgi.c,v 1.91 2007/01/27 13:09:16 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/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-2004, 2006-2007
15  *                the SourceForge 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.91  2007/01/27 13:09:16  fabiankeil
42  *    Add new config option "templdir" to
43  *    change the templates directory.
44  *
45  *    Revision 1.90  2007/01/25 13:47:26  fabiankeil
46  *    Added "forwarding-failed" template support for error_response().
47  *
48  *    Revision 1.89  2007/01/23 15:51:16  fabiankeil
49  *    Add favicon delivery functions.
50  *
51  *    Revision 1.88  2007/01/23 13:14:32  fabiankeil
52  *    - Map variables that aren't guaranteed to be
53  *      pure ASCII html_encoded.
54  *    - Use CGI_PREFIX to generate URL for user manual
55  *      CGI page to make sure CGI_SITE_2_PATH is included.
56  *
57  *    Revision 1.87  2007/01/22 15:34:13  fabiankeil
58  *    - "Protect" against a rather lame JavaScript-based
59  *      Privoxy detection "attack" and check the referrer
60  *      before delivering the CGI style sheet.
61  *    - Move referrer check for unsafe CGI pages into
62  *      referrer_is_safe() and log the result.
63  *    - Map @url@ in cgi-error-disabled page.
64  *      It's required for the "go there anyway" link.
65  *    - Mark *csp as immutable for grep_cgi_referrer().
66  *
67  *    Revision 1.86  2007/01/09 11:54:26  fabiankeil
68  *    Fix strdup() error handling in cgi_error_unknown()
69  *    and cgi_error_no_template(). Reported by Markus Elfring.
70  *
71  *    Revision 1.85  2007/01/05 14:19:02  fabiankeil
72  *    Handle pcrs_execute() errors in template_fill() properly.
73  *
74  *    Revision 1.84  2006/12/28 17:54:22  fabiankeil
75  *    Fixed gcc43 conversion warnings and replaced sprintf
76  *    calls with snprintf to give OpenBSD's gcc one less reason
77  *    to complain.
78  *
79  *    Revision 1.83  2006/12/17 19:35:19  fabiankeil
80  *    Escape ampersand in Privoxy menu.
81  *
82  *    Revision 1.82  2006/12/17 17:53:39  fabiankeil
83  *    Suppress the toggle link if remote toggling is disabled.
84  *
85  *    Revision 1.81  2006/12/09 13:49:16  fabiankeil
86  *    Fix configure option --disable-toggle.
87  *    Thanks to Peter Thoenen for reporting this.
88  *
89  *    Revision 1.80  2006/12/08 14:45:32  fabiankeil
90  *    Don't lose the FORCE_PREFIX in case of
91  *    connection problems. Fixes #612235.
92  *
93  *    Revision 1.79  2006/11/13 19:05:50  fabiankeil
94  *    Make pthread mutex locking more generic. Instead of
95  *    checking for OSX and OpenBSD, check for FEATURE_PTHREAD
96  *    and use mutex locking unless there is an _r function
97  *    available. Better safe than sorry.
98  *
99  *    Fixes "./configure --disable-pthread" and should result
100  *    in less threading-related problems on pthread-using platforms,
101  *    but it still doesn't fix BR#1122404.
102  *
103  *    Revision 1.78  2006/09/21 19:22:07  fabiankeil
104  *    Use CGI_PREFIX to check the referrer.
105  *    The check for "http://config.privoxy.org/" fails
106  *    if the user modified CGI_SITE_2_HOST.
107  *
108  *    Revision 1.77  2006/09/21 15:17:23  fabiankeil
109  *    Adjusted headers for Privoxy's cgi responses:
110  *    Don't set Last-Modified, Expires and Cache-Control
111  *    headers for redirects; always set "Connection: close".
112  *
113  *    Revision 1.76  2006/09/07 14:06:38  fabiankeil
114  *    Only predate the Last-Modified header for cgi responses
115  *    that are delivered with status code 404 or 503.
116  *
117  *    Revision 1.75  2006/09/07 11:56:39  fabiankeil
118  *    Mark cgi_send_user_manual as harmless,
119  *    to fix the access denied problem Hal spotted.
120  *    The manual has no secret content, therefore we
121  *    don't have to care about "secure" referrers.
122  *
123  *    Revision 1.74  2006/09/06 18:45:03  fabiankeil
124  *    Incorporate modified version of Roland Rosenfeld's patch to
125  *    optionally access the user-manual via Privoxy. Closes patch 679075.
126  *
127  *    Formatting changed to Privoxy style, added call to
128  *    cgi_error_no_template if the requested file doesn't
129  *    exist and modified check whether or not Privoxy itself
130  *    should serve the manual. Should work cross-platform now.
131  *
132  *    Revision 1.73  2006/08/03 02:46:41  david__schmidt
133  *    Incorporate Fabian Keil's patch work:\rhttp://www.fabiankeil.de/sourcecode/privoxy/
134  *
135  *    Revision 1.72  2006/07/18 14:48:45  david__schmidt
136  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
137  *    with what was really the latest development (the v_3_0_branch branch)
138  *
139  *    Revision 1.70.2.13  2004/02/17 13:30:23  oes
140  *    Moved cgi_error_disabled() from cgiedit.c to
141  *    cgi.c to re-enable build with --disable-editor.
142  *    Fixes Bug #892744. Thanks to Matthew Fischer
143  *    for spotting.
144  *
145  *    Revision 1.70.2.12  2003/12/17 16:33:16  oes
146  *     - Added new function cgi_redirect to handle creation of
147  *       HTTP redirect messages formerly repeated in the code.
148  *     - Send cgi_error_disabled instead of cgi_error_404 when
149  *       referrer check fails
150  *     - Dynamic content now gets Expires header field with date
151  *       in the past
152  *
153  *    Revision 1.70.2.11  2003/10/23 12:29:26  oes
154  *    Bugfix: Transparent PNG was not transparent. Thanks to
155  *    Dan Razzell of Starfish Systems for notice and new PNG.
156  *
157  *    Revision 1.70.2.10  2003/06/06 07:54:25  oes
158  *    Security fix: dspatch_known_cgi no longer considers an empty
159  *    referrer safe for critical CGIs, since malicious links could
160  *    reside on https:// locations which browsers don't advertize as
161  *    referrers. Closes bug #749916, thanks to Jeff Epler for the
162  *    hint. Goodbye One-Click[tm] toggling :-(
163  *
164  *    Revision 1.70.2.9  2003/05/08 15:11:31  oes
165  *    Nit
166  *
167  *    Revision 1.70.2.8  2003/04/29 13:33:51  oes
168  *    Killed a compiler warning on OSX
169  *
170  *    Revision 1.70.2.7  2003/04/03 13:50:58  oes
171  *    - Don't call cgi_error_disabled ifndef FEATURE_CGI_EDIT_ACTIONS
172  *      (fixes bug #710056)
173  *    - Show toggle info only if we have it
174  *
175  *    Revision 1.70.2.6  2003/03/12 01:26:25  david__schmidt
176  *    Move declaration of struct tm dummy outside of a control block so it is
177  *    accessible later on during snprintf in get_http_time.
178  *
179  *    Revision 1.70.2.5  2003/03/11 11:53:58  oes
180  *    Cosmetic: Renamed cryptic variable
181  *
182  *    Revision 1.70.2.4  2003/03/07 03:41:03  david__schmidt
183  *    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.
184  *
185  *    Revision 1.70.2.3  2002/11/28 18:14:32  oes
186  *    Disable access to critical CGIs via untrusted referrers.
187  *    This prevents users from being tricked by malicious websites
188  *    into making unintentional configuration changes:
189  *
190  *     - Added flag to each cgi_dispatcher that allows or denies
191  *       external linking
192  *     - Introduced proviorical function that greps for the
193  *       referrer header before regular header parsing happens
194  *     - Added safety check to dispatch_known_cgi. CGI is called
195  *       if (cgi harmless || no referrer || we are referrer).
196  *       Else a) toggle calls are modified not to change status and
197  *       b) all other calls are denied.
198  *
199  *    Revision 1.70.2.2  2002/11/12 16:20:37  oes
200  *    Added missing #ifdef FEATURE_TOGGLE around g_bToggleIJB; fixes bug #636651
201  *
202  *    Revision 1.70.2.1  2002/08/05 11:17:46  oes
203  *    Fixed Bug #587820, i.e. added workaround for IE bug that includes fragment identifier in (cgi) query
204  *
205  *    Revision 1.70  2002/05/19 11:33:20  jongfoster
206  *    If a CGI error was not handled, and propogated back to
207  *    dispatch_known_cgi(), then it was assumed to be "out of memory".
208  *    This gave a very misleading error message.
209  *
210  *    Now other errors will cause a simple message giving the error
211  *    number and asking the user to report a bug.
212  *
213  *    Bug report:
214  *    http://sourceforge.net/tracker/index.php?func=detail
215  *    &aid=557905&group_id=11118&atid=111118
216  *
217  *    Revision 1.69  2002/05/14 21:28:40  oes
218  *     - Fixed add_help_link to link to the (now split) actions
219  *       part of the config chapter
220  *     - Renamed helplink export to actions-help-prefix
221  *
222  *    Revision 1.68  2002/05/12 21:36:29  jongfoster
223  *    Correcting function comments
224  *
225  *    Revision 1.67  2002/04/30 12:02:07  oes
226  *    Nit: updated a comment
227  *
228  *    Revision 1.66  2002/04/26 18:32:57  jongfoster
229  *    Fixing a memory leak on error
230  *
231  *    Revision 1.65  2002/04/26 12:53:51  oes
232  *     - New function add_help_link
233  *     - default_exports now exports links to the user manual
234  *       and a prefix for links into the config chapter
235  *
236  *    Revision 1.64  2002/04/24 02:17:21  oes
237  *     - Better descriptions for CGIs
238  *     - Hide edit-actions, more shortcuts
239  *     - Moved get_char_param, get_string_param and get_number_param here
240  *       from cgiedit.c
241  *
242  *    Revision 1.63  2002/04/15 19:06:43  jongfoster
243  *    Typos
244  *
245  *    Revision 1.62  2002/04/10 19:59:46  jongfoster
246  *    Fixes to #include in templates:
247  *    - Didn't close main file if loading an included template fails.
248  *    - I'm paranoid and want to disallow "#include /etc/passwd".
249  *
250  *    Revision 1.61  2002/04/10 13:37:48  oes
251  *    Made templates modular: template_load now recursive with max depth 1
252  *
253  *    Revision 1.60  2002/04/08 20:50:25  swa
254  *    fixed JB spelling
255  *
256  *    Revision 1.59  2002/04/05 15:51:51  oes
257  *     - added send-stylesheet CGI
258  *     - bugfix: error-pages now get correct request protocol
259  *     - fixed
260  *     - kludged CGI descriptions and menu not to break JS syntax
261  *
262  *    Revision 1.58  2002/03/29 03:33:13  david__schmidt
263  *    Fix Mac OSX compiler warnings
264  *
265  *    Revision 1.57  2002/03/26 22:29:54  swa
266  *    we have a new homepage!
267  *
268  *    Revision 1.56  2002/03/24 17:50:46  jongfoster
269  *    Fixing compile error if actions file editor disabled
270  *
271  *    Revision 1.55  2002/03/24 16:55:06  oes
272  *    Making GIF checkerboard transparent
273  *
274  *    Revision 1.54  2002/03/24 16:18:15  jongfoster
275  *    Removing old logo
276  *
277  *    Revision 1.53  2002/03/24 16:06:00  oes
278  *    Correct transparency for checkerboard PNG. Thanks, Magnus!
279  *
280  *    Revision 1.52  2002/03/24 15:23:33  jongfoster
281  *    Name changes
282  *
283  *    Revision 1.51  2002/03/24 13:25:43  swa
284  *    name change related issues
285  *
286  *    Revision 1.50  2002/03/16 23:54:06  jongfoster
287  *    Adding graceful termination feature, to help look for memory leaks.
288  *    If you enable this (which, by design, has to be done by hand
289  *    editing config.h) and then go to http://i.j.b/die, then the program
290  *    will exit cleanly after the *next* request.  It should free all the
291  *    memory that was used.
292  *
293  *    Revision 1.49  2002/03/13 00:27:04  jongfoster
294  *    Killing warnings
295  *
296  *    Revision 1.48  2002/03/08 17:47:07  jongfoster
297  *    Adding comments
298  *
299  *    Revision 1.47  2002/03/08 16:41:33  oes
300  *    Added GIF images again
301  *
302  *    Revision 1.46  2002/03/07 03:48:38  oes
303  *     - Changed built-in images from GIF to PNG
304  *       (with regard to Unisys patent issue)
305  *     - Added a 4x4 pattern PNG which is less intrusive
306  *       than the logo but also clearly marks the deleted banners
307  *
308  *    Revision 1.45  2002/03/06 22:54:35  jongfoster
309  *    Automated function-comment nitpicking.
310  *
311  *    Revision 1.44  2002/03/05 22:43:45  david__schmidt
312  *    - Better error reporting on OS/2
313  *    - Fix double-slash comment (oops)
314  *
315  *    Revision 1.43  2002/03/05 21:33:45  david__schmidt
316  *    - Re-enable OS/2 building after new parms were added
317  *    - Fix false out of memory report when resolving CGI templates when no IP
318  *      address is available of failed attempt (a la no such domain)
319  *
320  *    Revision 1.42  2002/01/21 00:33:20  jongfoster
321  *    Replacing strsav() with the safer string_append() or string_join().
322  *    Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
323  *    Adding missing html_encode() to error message generators.
324  *    Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
325  *
326  *    Revision 1.41  2002/01/17 20:56:22  jongfoster
327  *    Replacing hard references to the URL of the config interface
328  *    with #defines from project.h
329  *
330  *    Revision 1.40  2002/01/09 14:26:46  oes
331  *    Added support for thread-safe gmtime_r call.
332  *
333  *    Revision 1.39  2001/11/16 00:48:13  jongfoster
334  *    Fixing a compiler warning
335  *
336  *    Revision 1.38  2001/11/13 00:31:21  jongfoster
337  *    - Adding new CGIs for use by non-JavaScript browsers:
338  *        edit-actions-url-form
339  *        edit-actions-add-url-form
340  *        edit-actions-remove-url-form
341  *    - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
342  *    - Fixing || bug.
343  *
344  *    Revision 1.37  2001/11/01 14:28:47  david__schmidt
345  *    Show enablement/disablement status in almost all templates.
346  *    There is a little trickiness here: apparent recursive resolution of
347  *    @if-enabled-then@ caused the toggle template to show status out-of-phase with
348  *    the actual enablement status.  So a similar construct,
349  *    @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
350  *    templates.
351  *
352  *    Revision 1.36  2001/10/26 17:33:27  oes
353  *    marginal bugfix
354  *
355  *    Revision 1.35  2001/10/23 21:48:19  jongfoster
356  *    Cleaning up error handling in CGI functions - they now send back
357  *    a HTML error page and should never cause a FATAL error.  (Fixes one
358  *    potential source of "denial of service" attacks).
359  *
360  *    CGI actions file editor that works and is actually useful.
361  *
362  *    Ability to toggle Junkbuster remotely using a CGI call.
363  *
364  *    You can turn off both the above features in the main configuration
365  *    file, e.g. if you are running a multi-user proxy.
366  *
367  *    Revision 1.34  2001/10/18 22:22:09  david__schmidt
368  *    Only show "Local support" on templates conditionally:
369  *      - if either 'admin-address' or 'proxy-info-url' are uncommented in config
370  *      - if not, no Local support section appears
371  *
372  *    Revision 1.33  2001/10/14 22:28:41  jongfoster
373  *    Fixing stupid typo.
374  *
375  *    Revision 1.32  2001/10/14 22:20:18  jongfoster
376  *    - Changes to CGI dispatching method to match CGI names exactly,
377  *      rather than doing a prefix match.
378  *    - No longer need to count the length of the CGI handler names by hand.
379  *    - Adding new handler for 404 error when disptching a CGI, if none of
380  *      the handlers match.
381  *    - Adding new handlers for CGI actionsfile editor.
382  *
383  *    Revision 1.31  2001/10/10 10:56:39  oes
384  *    Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
385  *
386  *    Revision 1.30  2001/10/02 15:30:57  oes
387  *    Introduced show-request cgi
388  *
389  *    Revision 1.29  2001/09/20 15:47:44  steudten
390  *
391  *    Fix BUG: Modify int size to size_t size in fill_template()
392  *     - removes big trouble on machines where sizeof(int) != sizeof(size_t).
393  *
394  *    Revision 1.28  2001/09/19 18:00:37  oes
395  *     - Deletef time() FIXME (Can't fail under Linux either, if
396  *       the argument is guaranteed to be in out address space,
397  *       which it is.)
398  *     - Fixed comments
399  *     - Pointer notation cosmetics
400  *     - Fixed a minor bug in template_fill(): Failiure of
401  *       pcrs_execute() now secure.
402  *
403  *    Revision 1.27  2001/09/16 17:08:54  jongfoster
404  *    Moving simple CGI functions from cgi.c to new file cgisimple.c
405  *
406  *    Revision 1.26  2001/09/16 15:47:37  jongfoster
407  *    First version of CGI-based edit interface.  This is very much a
408  *    work-in-progress, and you can't actually use it to edit anything
409  *    yet.  You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
410  *    to have any effect.
411  *
412  *    Revision 1.25  2001/09/16 15:02:35  jongfoster
413  *    Adding i.j.b/robots.txt.
414  *    Inlining add_stats() since it's only ever called from one place.
415  *
416  *    Revision 1.24  2001/09/16 11:38:01  jongfoster
417  *    Splitting fill_template() into 2 functions:
418  *    template_load() loads the file
419  *    template_fill() performs the PCRS regexps.
420  *    This is because the CGI edit interface has a "table row"
421  *    template which is used many times in the page - this
422  *    change means it's only loaded from disk once.
423  *
424  *    Revision 1.23  2001/09/16 11:16:05  jongfoster
425  *    Better error handling in dispatch_cgi() and parse_cgi_parameters()
426  *
427  *    Revision 1.22  2001/09/16 11:00:10  jongfoster
428  *    New function alloc_http_response, for symmetry with free_http_response
429  *
430  *    Revision 1.21  2001/09/13 23:53:03  jongfoster
431  *    Support for both static and dynamically generated CGI pages.
432  *    Correctly setting Last-Modified: and Expires: HTTP headers.
433  *
434  *    Revision 1.20  2001/09/13 23:40:36  jongfoster
435  *    (Cosmetic only) Indentation correction
436  *
437  *    Revision 1.19  2001/09/13 23:31:25  jongfoster
438  *    Moving image data to cgi.c rather than cgi.h.
439  *
440  *    Revision 1.18  2001/08/05 16:06:20  jongfoster
441  *    Modifiying "struct map" so that there are now separate header and
442  *    "map_entry" structures.  This means that functions which modify a
443  *    map no longer need to return a pointer to the modified map.
444  *    Also, it no longer reverses the order of the entries (which may be
445  *    important with some advanced template substitutions).
446  *
447  *    Revision 1.17  2001/08/05 15:57:38  oes
448  *    Adapted finish_http_response to new list_to_text
449  *
450  *    Revision 1.16  2001/08/01 21:33:18  jongfoster
451  *    Changes to fill_template() that reduce memory usage without having
452  *    an impact on performance.  I also renamed some variables so as not
453  *    to clash with the C++ keywords "new" and "template".
454  *
455  *    Revision 1.15  2001/08/01 21:19:22  jongfoster
456  *    Moving file version information to a separate CGI page.
457  *
458  *    Revision 1.14  2001/08/01 00:19:03  jongfoster
459  *    New function: map_conditional() for an if-then-else syntax.
460  *    Changing to use new version of show_defines()
461  *
462  *    Revision 1.13  2001/07/30 22:08:36  jongfoster
463  *    Tidying up #defines:
464  *    - All feature #defines are now of the form FEATURE_xxx
465  *    - Permanently turned off WIN_GUI_EDIT
466  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
467  *
468  *    Revision 1.12  2001/07/29 18:47:05  jongfoster
469  *    Adding missing #include "loadcfg.h"
470  *
471  *    Revision 1.11  2001/07/18 17:24:37  oes
472  *    Changed to conform to new pcrs interface
473  *
474  *    Revision 1.10  2001/07/13 13:53:13  oes
475  *    Removed all #ifdef PCRS and related code
476  *
477  *    Revision 1.9  2001/06/29 21:45:41  oes
478  *    Indentation, CRLF->LF, Tab-> Space
479  *
480  *    Revision 1.8  2001/06/29 13:21:46  oes
481  *    - Cosmetics: renamed and reordered functions, variables,
482  *      texts, improved comments  etc
483  *
484  *    - Removed ij_untrusted_url() The relevant
485  *      info is now part of the "untrusted" page,
486  *      which is generated by filters.c:trust_url()
487  *
488  *    - Generators of content now call finish_http_response()
489  *      themselves, making jcc.c:chat() a little less
490  *      cluttered
491  *
492  *    - Removed obsolete "Pragma: no-cache" from our headers
493  *
494  *    - http_responses now know their head length
495  *
496  *    - fill_template now uses the new interface to pcrs, so that
497  *       - long jobs (like whole files) no longer have to be assembled
498  *         in a fixed size buffer
499  *       - the new T (trivial) option is used, and the replacement may
500  *         contain Perl syntax backrefs without confusing pcrs
501  *
502  *    - Introduced default_exports() which generates a set of exports
503  *      common to all CGIs and other content generators
504  *
505  *    - Introduced convenience function map_block_killer()
506  *
507  *    - Introduced convenience function make_menu()
508  *
509  *    - Introduced CGI-like function error_response() which generates
510  *      the "No such domain" and "Connect failed" messages using the
511  *      CGI platform
512  *
513  *    - cgi_show_url_info:
514  *      - adapted to new CGI features
515  *      - form and answers now generated from same template
516  *      - http:// prefix in URL now OK
517  *
518  *    - cgi_show_status:
519  *      - adapted to new CGI features
520  *      - no longer uses csp->init_proxy_args
521  *
522  *    - cgi_default:
523  *      - moved menu generation to make_menu()
524  *
525  *    - add_stats now writes single export map entries instead
526  *      of a fixed string
527  *
528  *    - Moved redirect_url() to filters.c
529  *
530  *    - Fixed mem leak in free_http_response(), map_block_killer(),
531  *
532  *    - Removed logentry from cancelled commit
533  *
534  *    Revision 1.7  2001/06/09 10:51:58  jongfoster
535  *    Changing "show URL info" handler to new style.
536  *    Changing BUFSIZ ==> BUFFER_SIZE
537  *
538  *    Revision 1.6  2001/06/07 23:05:19  jongfoster
539  *    Removing code related to old forward and ACL files.
540  *
541  *    Revision 1.5  2001/06/05 19:59:16  jongfoster
542  *    Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
543  *
544  *    Revision 1.4  2001/06/04 10:41:52  swa
545  *    show version string of cgi.h and cgi.c
546  *
547  *    Revision 1.3  2001/06/03 19:12:16  oes
548  *    introduced new cgi handling
549  *
550  *    No revisions before 1.3
551  *
552  **********************************************************************/
553 \f
554
555 #include "config.h"
556
557 #include <stdio.h>
558 #include <sys/types.h>
559 #include <stdlib.h>
560 #include <ctype.h>
561 #include <string.h>
562 #include <limits.h>
563 #include <assert.h>
564
565 #ifdef _WIN32
566 #define snprintf _snprintf
567 #endif /* def _WIN32 */
568
569 #include "project.h"
570 #include "cgi.h"
571 #include "list.h"
572 #include "encode.h"
573 #include "ssplit.h"
574 #include "errlog.h"
575 #include "filters.h"
576 #include "miscutil.h"
577 #include "cgisimple.h"
578 #ifdef FEATURE_CGI_EDIT_ACTIONS
579 #include "cgiedit.h"
580 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
581 #include "loadcfg.h"
582 /* loadcfg.h is for global_toggle_state only */
583 #ifdef FEATURE_PTHREAD
584 #include "jcc.h"
585 /* jcc.h is for mutex semaphore globals only */
586 #endif /* def FEATURE_PTHREAD */
587 const char cgi_h_rcs[] = CGI_H_VERSION;
588
589 /*
590  * List of CGI functions: name, handler, description
591  * Note: Do NOT use single quotes in the description;
592  *       this will break the dynamic "blocked" template!
593  */
594 static const struct cgi_dispatcher cgi_dispatchers[] = {
595    { "",
596          cgi_default,
597          "Privoxy main page",
598          TRUE },
599 #ifdef FEATURE_GRACEFUL_TERMINATION
600    { "die", 
601          cgi_die,  
602          "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
603         "this is a one click Denial Of Service attack!!!</em>",
604          FALSE }, 
605 #endif
606    { "show-status", 
607          cgi_show_status,  
608 #ifdef FEATURE_CGI_EDIT_ACTIONS
609         "View &amp; change the current configuration",
610 #else
611         "View the current configuration",
612 #endif
613          TRUE }, 
614    { "show-version", 
615          cgi_show_version,  
616          "View the source code version numbers",
617           TRUE }, 
618    { "show-request", 
619          cgi_show_request,  
620          "View the request headers.",
621          TRUE }, 
622    { "show-url-info",
623          cgi_show_url_info, 
624          "Look up which actions apply to a URL and why",
625          TRUE },
626 #ifdef FEATURE_CGI_EDIT_ACTIONS
627 #ifdef FEATURE_TOGGLE
628    { "toggle",
629          cgi_toggle, 
630          "Toggle Privoxy on or off",
631          FALSE },
632 #endif /* def FEATURE_TOGGLE */
633    { "edit-actions", /* Edit the actions list */
634          cgi_edit_actions, 
635          NULL, FALSE },
636    { "eaa", /* Shortcut for edit-actions-add-url-form */
637          cgi_edit_actions_add_url_form, 
638          NULL, FALSE },
639    { "eau", /* Shortcut for edit-actions-url-form */
640          cgi_edit_actions_url_form, 
641          NULL, FALSE },
642    { "ear", /* Shortcut for edit-actions-remove-url-form */
643          cgi_edit_actions_remove_url_form, 
644          NULL, FALSE },
645    { "eal", /* Shortcut for edit-actions-list */
646          cgi_edit_actions_list, 
647          NULL, FALSE },
648    { "eafu", /* Shortcut for edit-actions-for-url */
649          cgi_edit_actions_for_url, 
650          NULL, FALSE },
651    { "eas", /* Shortcut for edit-actions-submit */
652          cgi_edit_actions_submit, 
653          NULL, FALSE },
654    { "easa", /* Shortcut for edit-actions-section-add */
655          cgi_edit_actions_section_add, 
656          NULL, FALSE  },
657    { "easr", /* Shortcut for edit-actions-section-remove */
658          cgi_edit_actions_section_remove, 
659          NULL, FALSE  },
660    { "eass", /* Shortcut for edit-actions-section-swap */
661          cgi_edit_actions_section_swap, 
662          NULL, FALSE  },
663    { "edit-actions-for-url",
664          cgi_edit_actions_for_url, 
665          NULL, FALSE  /* Edit the actions for (a) specified URL(s) */ },
666    { "edit-actions-list",
667          cgi_edit_actions_list, 
668          NULL, TRUE /* Edit the actions list */ },
669    { "edit-actions-submit",
670          cgi_edit_actions_submit, 
671          NULL, FALSE /* Change the actions for (a) specified URL(s) */ },
672    { "edit-actions-url",
673          cgi_edit_actions_url, 
674          NULL, FALSE /* Change a URL pattern in the actionsfile */ },
675    { "edit-actions-url-form",
676          cgi_edit_actions_url_form, 
677          NULL, FALSE /* Form to change a URL pattern in the actionsfile */ },
678    { "edit-actions-add-url",
679          cgi_edit_actions_add_url, 
680          NULL, FALSE /* Add a URL pattern to the actionsfile */ },
681    { "edit-actions-add-url-form",
682          cgi_edit_actions_add_url_form, 
683          NULL, FALSE /* Form to add a URL pattern to the actionsfile */ },
684    { "edit-actions-remove-url",
685          cgi_edit_actions_remove_url, 
686          NULL, FALSE /* Remove a URL pattern from the actionsfile */ },
687    { "edit-actions-remove-url-form",
688          cgi_edit_actions_remove_url_form, 
689          NULL, FALSE /* Form to remove a URL pattern from the actionsfile */ },
690    { "edit-actions-section-add",
691          cgi_edit_actions_section_add, 
692          NULL, FALSE /* Remove a section from the actionsfile */ },
693    { "edit-actions-section-remove",
694          cgi_edit_actions_section_remove, 
695          NULL, FALSE /* Remove a section from the actionsfile */ },
696    { "edit-actions-section-swap",
697          cgi_edit_actions_section_swap, 
698          NULL, FALSE /* Swap two sections in the actionsfile */ },
699 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
700    { "error-favicon.ico", 
701          cgi_send_error_favicon,  
702          NULL, TRUE /* Sends the favicon image for error pages. */ },
703    { "favicon.ico", 
704          cgi_send_default_favicon,  
705          NULL, TRUE /* Sends the default favicon image. */ },
706    { "robots.txt", 
707          cgi_robots_txt,  
708          NULL, TRUE /* Sends a robots.txt file to tell robots to go away. */ }, 
709    { "send-banner",
710          cgi_send_banner, 
711          NULL, TRUE /* Send a built-in image */ },
712    { "send-stylesheet",
713          cgi_send_stylesheet, 
714          NULL, FALSE /* Send templates/cgi-style.css */ },
715    { "t",
716          cgi_transparent_image, 
717          NULL, TRUE /* Send a transparent image (short name) */ },
718    { "user-manual",
719           cgi_send_user_manual,
720           NULL, TRUE /* Send user-manual */ },
721    { NULL, /* NULL Indicates end of list and default page */
722          cgi_error_404,
723          NULL, TRUE /* Unknown CGI page */ }
724 };
725
726
727 /*
728  * Built-in images for ad replacement
729  *
730  * Hint: You can encode your own images like this:
731  * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
732  */
733
734 #ifdef FEATURE_NO_GIFS
735
736 /*
737  * Checkerboard pattern, as a PNG.
738  */
739 const char image_pattern_data[] =
740    "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
741    "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
742    "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
743    "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
744    "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
745    "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
746    "\000\000\000\111\105\116\104\256\102\140\202";
747
748 /*
749  * 1x1 transparant PNG.
750  */
751 const char image_blank_data[] =
752  "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
753  "\000\000\000\001\000\000\000\001\001\003\000\000\000\045\333\126"
754  "\312\000\000\000\003\120\114\124\105\377\377\377\247\304\033\310"
755  "\000\000\000\001\164\122\116\123\000\100\346\330\146\000\000\000"
756  "\001\142\113\107\104\000\210\005\035\110\000\000\000\012\111\104"
757  "\101\124\170\001\143\140\000\000\000\002\000\001\163\165\001\030"
758  "\000\000\000\000\111\105\116\104\256\102\140\202";
759 #else
760
761 /*
762  * Checkerboard pattern, as a GIF.
763  */
764 const char image_pattern_data[] =
765    "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
766    "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
767    "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
768    "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
769    "\270\005\000\073";
770
771 /*
772  * 1x1 transparant GIF.
773  */
774 const char image_blank_data[] =
775    "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
776    "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
777    "\000\001\000\000\002\002D\001\000;";
778 #endif
779
780 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
781 const size_t image_blank_length   = sizeof(image_blank_data) - 1;
782
783
784 static struct http_response cgi_error_memory_response[1];
785
786 static struct http_response *dispatch_known_cgi(struct client_state * csp,
787                                                 const char * path);
788 static struct map *parse_cgi_parameters(char *argstring);
789
790
791 /*********************************************************************
792  * 
793  * Function    :  dispatch_cgi
794  *
795  * Description :  Checks if a request URL has either the magical
796  *                hostname CGI_SITE_1_HOST (usually http://p.p/) or
797  *                matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
798  *                http://config.privoxy.org/). If so, it passes
799  *                the (rest of the) path onto dispatch_known_cgi, which
800  *                calls the relevant CGI handler function.
801  *
802  * Parameters  :
803  *          1  :  csp = Current client state (buffers, headers, etc...)
804  *
805  * Returns     :  http_response if match, NULL if nonmatch or handler fail
806  *
807  *********************************************************************/
808 struct http_response *dispatch_cgi(struct client_state *csp)
809 {
810    const char *host = csp->http->host;
811    const char *path = csp->http->path;
812
813    /*
814     * Should we intercept ?
815     */
816
817    /* Note: "example.com" and "example.com." are equivalent hostnames. */
818
819    /* Either the host matches CGI_SITE_1_HOST ..*/
820    if (   ( (0 == strcmpic(host, CGI_SITE_1_HOST))
821          || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
822        && (path[0] == '/') )
823    {
824       /* ..then the path will all be for us.  Remove leading '/' */
825       path++;
826    }
827    /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
828    else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
829             || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
830           && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
831    {
832       /* take everything following CGI_SITE_2_PATH */
833       path += strlen(CGI_SITE_2_PATH);
834       if (*path == '/')
835       {
836          /* skip the forward slash after CGI_SITE_2_PATH */
837          path++;
838       }
839       else if (*path != '\0')
840       {
841          /*
842           * weirdness: URL is /configXXX, where XXX is some string
843           * Do *NOT* intercept.
844           */
845          return NULL;
846       }
847    }
848    else
849    {
850       /* Not a CGI */
851       return NULL;
852    }
853
854    /* 
855     * This is a CGI call.
856     */
857
858    return dispatch_known_cgi(csp, path);
859 }
860
861
862 /*********************************************************************
863  *
864  * Function    :  grep_cgi_referrer
865  *
866  * Description :  Ugly provisorical fix that greps the value of the
867  *                referer HTTP header field out of a linked list of
868  *                strings like found at csp->headers. Will disappear
869  *                in Privoxy 3.1.
870  *
871  *                FIXME: csp->headers ought to be csp->http->headers
872  *                FIXME: Parsing all client header lines should
873  *                       happen right after the request is received!
874  *
875  * Parameters  :
876  *          1  :  csp = Current client state (buffers, headers, etc...)
877  *
878  * Returns     :  pointer to value (no copy!), or NULL if none found.
879  *
880  *********************************************************************/
881 char *grep_cgi_referrer(const struct client_state *csp)
882 {
883    struct list_entry *p;
884
885    for (p = csp->headers->first; p != NULL; p = p->next)
886    {
887       if (p->str == NULL) continue;
888       if (strncmpic(p->str, "Referer: ", 9) == 0)
889       {
890          return ((p->str) + 9);
891       }
892    }
893    return NULL;
894
895 }
896
897
898 /*********************************************************************
899  * 
900  * Function    :  referrer_is_safe
901  *
902  * Description :  Decides whether we trust the Referer for
903  *                CGI pages which are only meant to be reachable
904  *                through Privoxy's web interface directly.
905  *
906  * Parameters  :
907  *          1  :  csp = Current client state (buffers, headers, etc...)
908  *
909  * Returns     :  TRUE  if the referrer is safe, or
910  *                FALSE if the referrer is unsafe or not set.
911  *
912  *********************************************************************/
913 int referrer_is_safe (const struct client_state *csp)
914 {
915    char *referrer;
916    const char alternative_prefix[] = "http://" CGI_SITE_1_HOST "/";
917
918    referrer = grep_cgi_referrer(csp);
919
920    if (NULL == referrer)
921    {
922       /* No referrer, no access  */
923       log_error(LOG_LEVEL_ERROR, "Denying access to %s. No referrer found.",
924          csp->http->url);
925    }
926    else if ((0 == strncmp(referrer, CGI_PREFIX, sizeof(CGI_PREFIX)-1)
927          || (0 == strncmp(referrer, alternative_prefix, strlen(alternative_prefix)))))
928    {
929       /* Trustworthy referrer */
930       log_error(LOG_LEVEL_CGI, "Granting access to %s, referrer %s is trustworthy.",
931          csp->http->url, referrer);
932
933       return TRUE;
934    }
935    else
936    {
937       /* Untrustworthy referrer */
938       log_error(LOG_LEVEL_ERROR, "Denying access to %s, referrer %s isn't trustworthy.",
939          csp->http->url, referrer);
940    }
941
942    return FALSE;
943
944 }
945
946 /*********************************************************************
947  * 
948  * Function    :  dispatch_known_cgi
949  *
950  * Description :  Processes a CGI once dispatch_cgi has determined that
951  *                it matches one of the magic prefixes. Parses the path
952  *                as a cgi name plus query string, prepares a map that
953  *                maps CGI parameter names to their values, initializes
954  *                the http_response struct, and calls the relevant CGI
955  *                handler function.
956  *
957  * Parameters  :
958  *          1  :  csp = Current client state (buffers, headers, etc...)
959  *          2  :  path = Path of CGI, with the CGI prefix removed.
960  *                       Should not have a leading "/".
961  *
962  * Returns     :  http_response, or NULL on handler failure or out of
963  *                memory.
964  *
965  *********************************************************************/
966 static struct http_response *dispatch_known_cgi(struct client_state * csp,
967                                                 const char * path)
968 {
969    const struct cgi_dispatcher *d;
970    struct map *param_list;
971    struct http_response *rsp;
972    char *query_args_start;
973    char *path_copy;
974    jb_err err;
975
976    if (NULL == (path_copy = strdup(path)))
977    {
978       return cgi_error_memory();
979    }
980    query_args_start = path_copy;
981    while (*query_args_start && *query_args_start != '?' && *query_args_start != '/')
982    {
983       query_args_start++;
984    }
985    if (*query_args_start == '/') 
986    {
987       *query_args_start++ = '\0';
988       if ((param_list = new_map()))
989       {
990          map(param_list, "file", 1, url_decode(query_args_start), 0);
991       }
992    }
993    else
994    {
995       if (*query_args_start == '?')
996       {
997          *query_args_start++ = '\0';
998       }
999       if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
1000       {
1001          free(path_copy);
1002          return cgi_error_memory();
1003       }
1004    }
1005
1006    /*
1007     * At this point:
1008     * path_copy        = CGI call name
1009     * param_list       = CGI params, as map
1010     */
1011
1012    /* Get mem for response or fail*/
1013    if (NULL == (rsp = alloc_http_response()))
1014    {
1015       free(path_copy);
1016       free_map(param_list);
1017       return cgi_error_memory();
1018    }
1019
1020    log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
1021    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", 
1022                             csp->ip_addr_str, csp->http->cmd); 
1023
1024    /* 
1025     * Find and start the right CGI function
1026     */
1027    d = cgi_dispatchers;
1028    for (;;)
1029    {
1030       if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
1031       {
1032          /*
1033           * If the called CGI is either harmless, or referred
1034           * from a trusted source, start it.
1035           */
1036          if (d->harmless || referrer_is_safe(csp))
1037          {
1038             err = (d->handler)(csp, rsp, param_list);
1039          }
1040          else
1041          {
1042             /*
1043              * Else, modify toggle calls so that they only display
1044              * the status, and deny all other calls.
1045              */
1046             if (0 == strcmp(path_copy, "toggle"))
1047             {
1048                unmap(param_list, "set");
1049                err = (d->handler)(csp, rsp, param_list);
1050             }
1051             else
1052             {
1053                err = cgi_error_disabled(csp, rsp);
1054             }
1055          }
1056
1057          free(path_copy);
1058          free_map(param_list);
1059
1060          if (err == JB_ERR_CGI_PARAMS)
1061          {
1062             err = cgi_error_bad_param(csp, rsp);
1063          }
1064          if (err && (err != JB_ERR_MEMORY))
1065          {
1066             /* Unexpected error! Shouldn't get here */
1067             log_error(LOG_LEVEL_ERROR, "Unexpected CGI error %d in top-level handler.  Please file a bug report!", err);
1068             err = cgi_error_unknown(csp, rsp, err);
1069          }
1070          if (!err)
1071          {
1072             /* It worked */
1073             return finish_http_response(csp, rsp);
1074          }
1075          else
1076          {
1077             /* Error in handler, probably out-of-memory */
1078             free_http_response(rsp);
1079             return cgi_error_memory();
1080          }
1081       }
1082       d++;
1083    }
1084 }
1085    
1086         
1087 /*********************************************************************
1088  *
1089  * Function    :  parse_cgi_parameters
1090  *
1091  * Description :  Parse a URL-encoded argument string into name/value
1092  *                pairs and store them in a struct map list.
1093  *
1094  * Parameters  :
1095  *          1  :  argstring = string to be parsed.  Will be trashed.
1096  *
1097  * Returns     :  pointer to param list, or NULL if out of memory.
1098  *
1099  *********************************************************************/
1100 static struct map *parse_cgi_parameters(char *argstring)
1101 {
1102    char *p;
1103    char *vector[BUFFER_SIZE];
1104    int pairs, i;
1105    struct map *cgi_params;
1106
1107    if (NULL == (cgi_params = new_map()))
1108    {
1109       return NULL;
1110    }
1111
1112    /* 
1113     * IE 5 does, of course, violate RFC 2316 Sect 4.1 and sends
1114     * the fragment identifier along with the request, so we must
1115     * cut it off here, so it won't pollute the CGI params:
1116     */
1117    if (NULL != (p = strchr(argstring, '#')))
1118    {
1119       *p = '\0';
1120    }
1121
1122    pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
1123
1124    for (i = 0; i < pairs; i++)
1125    {
1126       if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
1127       {
1128          *p = '\0';
1129          if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
1130          {
1131             free_map(cgi_params);
1132             return NULL;
1133          }
1134       }
1135    }
1136
1137    return cgi_params;
1138
1139 }
1140
1141
1142 /*********************************************************************
1143  *
1144  * Function    :  get_char_param
1145  *
1146  * Description :  Get a single-character parameter passed to a CGI
1147  *                function.
1148  *
1149  * Parameters  :
1150  *          1  :  parameters = map of cgi parameters
1151  *          2  :  param_name = The name of the parameter to read
1152  *
1153  * Returns     :  Uppercase character on success, '\0' on error.
1154  *
1155  *********************************************************************/
1156 char get_char_param(const struct map *parameters,
1157                     const char *param_name)
1158 {
1159    char ch;
1160
1161    assert(parameters);
1162    assert(param_name);
1163
1164    ch = *(lookup(parameters, param_name));
1165    if ((ch >= 'a') && (ch <= 'z'))
1166    {
1167       ch = (char)(ch - 'a' + 'A');
1168    }
1169
1170    return ch;
1171 }
1172
1173
1174 /*********************************************************************
1175  *
1176  * Function    :  get_string_param
1177  *
1178  * Description :  Get a string paramater, to be used as an
1179  *                ACTION_STRING or ACTION_MULTI paramater.
1180  *                Validates the input to prevent stupid/malicious
1181  *                users from corrupting their action file.
1182  *
1183  * Parameters  :
1184  *          1  :  parameters = map of cgi parameters
1185  *          2  :  param_name = The name of the parameter to read
1186  *          3  :  pparam = destination for paramater.  Allocated as
1187  *                part of the map "parameters", so don't free it.
1188  *                Set to NULL if not specified.
1189  *
1190  * Returns     :  JB_ERR_OK         on success, or if the paramater
1191  *                                  was not specified.
1192  *                JB_ERR_MEMORY     on out-of-memory.
1193  *                JB_ERR_CGI_PARAMS if the paramater is not valid.
1194  *
1195  *********************************************************************/
1196 jb_err get_string_param(const struct map *parameters,
1197                         const char *param_name,
1198                         const char **pparam)
1199 {
1200    const char *param;
1201    const char *s;
1202    char ch;
1203
1204    assert(parameters);
1205    assert(param_name);
1206    assert(pparam);
1207
1208    *pparam = NULL;
1209
1210    param = lookup(parameters, param_name);
1211    if (!*param)
1212    {
1213       return JB_ERR_OK;
1214    }
1215
1216    if (strlen(param) >= CGI_PARAM_LEN_MAX)
1217    {
1218       /*
1219        * Too long.
1220        *
1221        * Note that the length limit is arbitrary, it just seems
1222        * sensible to limit it to *something*.  There's no
1223        * technical reason for any limit at all.
1224        */
1225       return JB_ERR_CGI_PARAMS;
1226    }
1227
1228    /* Check every character to see if it's legal */
1229    s = param;
1230    while ((ch = *s++) != '\0')
1231    {
1232       if ( ((unsigned char)ch < (unsigned char)' ')
1233         || (ch == '}') )
1234       {
1235          /* Probable hack attempt, or user accidentally used '}'. */
1236          return JB_ERR_CGI_PARAMS;
1237       }
1238    }
1239
1240    /* Success */
1241    *pparam = param;
1242
1243    return JB_ERR_OK;
1244 }
1245
1246
1247 /*********************************************************************
1248  *
1249  * Function    :  get_number_param
1250  *
1251  * Description :  Get a non-negative integer from the parameters
1252  *                passed to a CGI function.
1253  *
1254  * Parameters  :
1255  *          1  :  csp = Current client state (buffers, headers, etc...)
1256  *          2  :  parameters = map of cgi parameters
1257  *          3  :  name = Name of CGI parameter to read
1258  *          4  :  pvalue = destination for value.
1259  *                         Set to -1 on error.
1260  *
1261  * Returns     :  JB_ERR_OK         on success
1262  *                JB_ERR_MEMORY     on out-of-memory
1263  *                JB_ERR_CGI_PARAMS if the parameter was not specified
1264  *                                  or is not valid.
1265  *
1266  *********************************************************************/
1267 jb_err get_number_param(struct client_state *csp,
1268                         const struct map *parameters,
1269                         char *name,
1270                         unsigned *pvalue)
1271 {
1272    const char *param;
1273    char ch;
1274    unsigned value;
1275
1276    assert(csp);
1277    assert(parameters);
1278    assert(name);
1279    assert(pvalue);
1280
1281    *pvalue = 0; 
1282
1283    param = lookup(parameters, name);
1284    if (!*param)
1285    {
1286       return JB_ERR_CGI_PARAMS;
1287    }
1288
1289    /* We don't use atoi because I want to check this carefully... */
1290
1291    value = 0;
1292    while ((ch = *param++) != '\0')
1293    {
1294       if ((ch < '0') || (ch > '9'))
1295       {
1296          return JB_ERR_CGI_PARAMS;
1297       }
1298
1299       ch = (char)(ch - '0');
1300
1301       /* Note:
1302        *
1303        * <limits.h> defines UINT_MAX
1304        *
1305        * (UINT_MAX - ch) / 10 is the largest number that
1306        *     can be safely multiplied by 10 then have ch added.
1307        */
1308       if (value > ((UINT_MAX - (unsigned)ch) / 10U))
1309       {
1310          return JB_ERR_CGI_PARAMS;
1311       }
1312
1313       value = value * 10 + (unsigned)ch;
1314    }
1315
1316    /* Success */
1317    *pvalue = value;
1318
1319    return JB_ERR_OK;
1320
1321 }
1322
1323
1324 /*********************************************************************
1325  *
1326  * Function    :  error_response
1327  *
1328  * Description :  returns an http_response that explains the reason
1329  *                why a request failed.
1330  *
1331  * Parameters  :
1332  *          1  :  csp = Current client state (buffers, headers, etc...)
1333  *          2  :  templatename = Which template should be used for the answer
1334  *          3  :  sys_err = system error number
1335  *
1336  * Returns     :  A http_response.  If we run out of memory, this
1337  *                will be cgi_error_memory().
1338  *
1339  *********************************************************************/
1340 struct http_response *error_response(struct client_state *csp,
1341                                      const char *templatename,
1342                                      int sys_err)
1343 {
1344    jb_err err;
1345    struct http_response *rsp;
1346    struct map *exports = default_exports(csp, NULL);
1347    char *path = NULL;
1348
1349    if (exports == NULL)
1350    {
1351       return cgi_error_memory();
1352    }
1353
1354    if (NULL == (rsp = alloc_http_response()))
1355    {
1356       free_map(exports);
1357       return cgi_error_memory();
1358    }
1359
1360    if (csp->flags & CSP_FLAG_FORCED)
1361    {
1362       path = strdup(FORCE_PREFIX);
1363    }
1364    else
1365    {
1366       path = strdup("");
1367    }
1368    err = string_append(&path, csp->http->path);
1369
1370    if (!err) err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1371    if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1372    if (!err) err = map(exports, "path", 1, html_encode_and_free_original(path), 0);
1373    if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1374    if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1); 
1375    if (!err)
1376    {
1377      err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1378      if (err)
1379      {
1380        /* Some failures, like "404 no such domain", don't have an IP address. */
1381        err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1382      }
1383    }
1384
1385
1386    if (err)
1387    {
1388       free_map(exports);
1389       free_http_response(rsp);
1390       return cgi_error_memory();
1391    }
1392
1393    if (!strcmp(templatename, "no-such-domain"))
1394    {
1395       rsp->status = strdup("404 No such domain");
1396       if (rsp->status == NULL)
1397       {
1398          free_map(exports);
1399          free_http_response(rsp);
1400          return cgi_error_memory();
1401       }
1402    }
1403    else if (!strcmp(templatename, "forwarding-failed"))
1404    {
1405       const struct forward_spec * fwd = forward_url(csp->http, csp);
1406       if (fwd == NULL)
1407       {
1408          log_error(LOG_LEVEL_FATAL, "gateway spec is NULL. This shouldn't happen!");
1409          /* Never get here - LOG_LEVEL_FATAL causes program exit */
1410       }
1411
1412       /*
1413        * XXX: While the template is called forwarding-failed,
1414        * it currently only handles socks forwarding failures.
1415        */
1416       assert(fwd->type != SOCKS_NONE);
1417
1418       /*
1419        * Map failure reason, forwarding type and forwarder.
1420        */
1421       if (NULL == csp->error_message)
1422       {
1423          /*
1424           * Either we forgot to record the failure reason,
1425           * or the memory allocation failed.
1426           */
1427          log_error(LOG_LEVEL_ERROR, "Socks failure reason missing.");
1428          csp->error_message = strdup("Failure reason missing. Check the log file for details.");
1429       }
1430       if (!err) err = map(exports, "gateway", 1, fwd->gateway_host, 1);
1431       if (!err) map(exports, "forwarding-type", 1, (fwd->type == SOCKS_4) ?
1432                    "socks4-" : "socks4a-", 1);
1433       if (!err) err = map(exports, "error-message", 1, html_encode(csp->error_message), 0);
1434
1435       if (!err) rsp->status = strdup("503 Forwarding failure");
1436       if ((rsp->status == NULL) || (NULL == csp->error_message) || err)
1437       {
1438          free_map(exports);
1439          free_http_response(rsp);
1440          return cgi_error_memory();
1441       }
1442    }
1443    else if (!strcmp(templatename, "connect-failed"))
1444    {
1445       rsp->status = strdup("503 Connect failed");
1446       if (rsp->status == NULL)
1447       {
1448          free_map(exports);
1449          free_http_response(rsp);
1450          return cgi_error_memory();
1451       }
1452    }
1453
1454    err = template_fill_for_cgi(csp, templatename, exports, rsp);
1455    if (err)
1456    {
1457       free_http_response(rsp);
1458       return cgi_error_memory();
1459    }
1460
1461    return finish_http_response(csp, rsp);
1462 }
1463
1464
1465 /*********************************************************************
1466  *
1467  * Function    :  cgi_error_disabled
1468  *
1469  * Description :  CGI function that is called to generate an error
1470  *                response if the actions editor or toggle CGI are
1471  *                accessed despite having being disabled at compile-
1472  *                or run-time, or if the user followed an untrusted link
1473  *                to access a unsafe CGI feature that is only reachable
1474  *                through Privoxy directly.
1475  *
1476  * Parameters  :
1477  *          1  :  csp = Current client state (buffers, headers, etc...)
1478  *          2  :  rsp = http_response data structure for output
1479  *
1480  * CGI Parameters : none
1481  *
1482  * Returns     :  JB_ERR_OK on success
1483  *                JB_ERR_MEMORY on out-of-memory error.
1484  *
1485  *********************************************************************/
1486 jb_err cgi_error_disabled(struct client_state *csp,
1487                           struct http_response *rsp)
1488 {
1489    struct map *exports;
1490
1491    assert(csp);
1492    assert(rsp);
1493
1494    if (NULL == (exports = default_exports(csp, "cgi-error-disabled")))
1495    {
1496       return JB_ERR_MEMORY;
1497    }
1498    if (map(exports, "url", 1, html_encode(csp->http->url), 0))
1499    {
1500       /* Not important enough to do anything */
1501       log_error(LOG_LEVEL_ERROR, "Failed to fill in url.");
1502    }
1503
1504    return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
1505 }
1506
1507
1508 /*********************************************************************
1509  *
1510  * Function    :  cgi_init_error_messages
1511  *
1512  * Description :  Call at the start of the program to initialize
1513  *                the error message used by cgi_error_memory().
1514  *
1515  * Parameters  :  N/A
1516  *
1517  * Returns     :  N/A
1518  *
1519  *********************************************************************/
1520 void cgi_init_error_messages(void)
1521 {
1522    memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1523    cgi_error_memory_response->head =
1524       "HTTP/1.0 500 Internal Privoxy Error\r\n"
1525       "Content-Type: text/html\r\n"
1526       "\r\n";
1527    cgi_error_memory_response->body =
1528       "<html>\r\n"
1529       "<head>\r\n"
1530       " <title>500 Internal Privoxy Error</title>\r\n"
1531       " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1532       "</head>\r\n"
1533       "<body>\r\n"
1534       "<h1>500 Internal Privoxy Error</h1>\r\n"
1535       "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1536       "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1537       "</body>\r\n"
1538       "</html>\r\n";
1539
1540    cgi_error_memory_response->head_length =
1541       strlen(cgi_error_memory_response->head);
1542    cgi_error_memory_response->content_length =
1543       strlen(cgi_error_memory_response->body);
1544 }
1545
1546
1547 /*********************************************************************
1548  *
1549  * Function    :  cgi_error_memory
1550  *
1551  * Description :  Called if a CGI function runs out of memory.
1552  *                Returns a statically-allocated error response.
1553  *
1554  * Parameters  :  N/A
1555  *
1556  * Returns     :  http_response data structure for output.  This is
1557  *                statically allocated, for obvious reasons.
1558  *
1559  *********************************************************************/
1560 struct http_response *cgi_error_memory(void)
1561 {
1562    /* assert that it's been initialized. */
1563    assert(cgi_error_memory_response->head);
1564
1565    return cgi_error_memory_response;
1566 }
1567
1568
1569 /*********************************************************************
1570  *
1571  * Function    :  cgi_error_no_template
1572  *
1573  * Description :  Almost-CGI function that is called if a template
1574  *                cannot be loaded.  Note this is not a true CGI,
1575  *                it takes a template name rather than a map of 
1576  *                parameters.
1577  *
1578  * Parameters  :
1579  *          1  :  csp = Current client state (buffers, headers, etc...)
1580  *          2  :  rsp = http_response data structure for output
1581  *          3  :  template_name = Name of template that could not
1582  *                                be loaded.
1583  *
1584  * Returns     :  JB_ERR_OK on success
1585  *                JB_ERR_MEMORY on out-of-memory error.  
1586  *
1587  *********************************************************************/
1588 jb_err cgi_error_no_template(struct client_state *csp,
1589                              struct http_response *rsp,
1590                              const char *template_name)
1591 {
1592    static const char status[] =
1593       "500 Internal Privoxy Error";
1594    static const char body_prefix[] =
1595       "<html>\r\n"
1596       "<head>\r\n"
1597       " <title>500 Internal Privoxy Error</title>\r\n"
1598       " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1599       "</head>\r\n"
1600       "<body>\r\n"
1601       "<h1>500 Internal Privoxy Error</h1>\r\n"
1602       "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1603       "<p><b>Could not load template file <code>";
1604    static const char body_suffix[] =
1605       "</code> or one of it's included components.</b></p>\r\n"
1606       "<p>Please contact your proxy administrator.</p>\r\n"
1607       "<p>If you are the proxy administrator, please put the required file(s)"
1608       "in the <code><i>(confdir)</i>/templates</code> directory.  The "
1609       "location of the <code><i>(confdir)</i></code> directory "
1610       "is specified in the main Privoxy <code>config</code> "
1611       "file.  (It's typically the Privoxy install directory"
1612 #ifndef _WIN32
1613       ", or <code>/etc/privoxy/</code>"
1614 #endif /* ndef _WIN32 */
1615       ").</p>\r\n"
1616       "</body>\r\n"
1617       "</html>\r\n";
1618
1619    assert(csp);
1620    assert(rsp);
1621    assert(template_name);
1622
1623    /* Reset rsp, if needed */
1624    freez(rsp->status);
1625    freez(rsp->head);
1626    freez(rsp->body);
1627    rsp->content_length = 0;
1628    rsp->head_length = 0;
1629    rsp->is_static = 0;
1630
1631    rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1632    if (rsp->body == NULL)
1633    {
1634       return JB_ERR_MEMORY;
1635    }
1636    strcpy(rsp->body, body_prefix);
1637    strcat(rsp->body, template_name);
1638    strcat(rsp->body, body_suffix);
1639
1640    rsp->status = strdup(status);
1641    if (rsp->status == NULL)
1642    {
1643       return JB_ERR_MEMORY;
1644    }
1645
1646    return JB_ERR_OK;
1647 }
1648
1649
1650 /*********************************************************************
1651  *
1652  * Function    :  cgi_error_unknown
1653  *
1654  * Description :  Almost-CGI function that is called if an unexpected
1655  *                error occurs in the top-level CGI dispatcher.
1656  *                In this context, "unexpected" means "anything other
1657  *                than JB_ERR_MEMORY or JB_ERR_CGI_PARAMS" - CGIs are
1658  *                expected to handle all other errors internally,
1659  *                since they can give more relavent error messages
1660  *                that way.
1661  *
1662  *                Note this is not a true CGI, it takes an error
1663  *                code rather than a map of parameters.
1664  *
1665  * Parameters  :
1666  *          1  :  csp = Current client state (buffers, headers, etc...)
1667  *          2  :  rsp = http_response data structure for output
1668  *          3  :  error_to_report = Error code to report.
1669  *
1670  * Returns     :  JB_ERR_OK on success
1671  *                JB_ERR_MEMORY on out-of-memory error.  
1672  *
1673  *********************************************************************/
1674 jb_err cgi_error_unknown(struct client_state *csp,
1675                          struct http_response *rsp,
1676                          jb_err error_to_report)
1677 {
1678    static const char status[] =
1679       "500 Internal Privoxy Error";
1680    static const char body_prefix[] =
1681       "<html>\r\n"
1682       "<head>\r\n"
1683       " <title>500 Internal Privoxy Error</title>\r\n"
1684       " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">"
1685       "</head>\r\n"
1686       "<body>\r\n"
1687       "<h1>500 Internal Privoxy Error</h1>\r\n"
1688       "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1689       "<p><b>Unexpected internal error: ";
1690    static const char body_suffix[] =
1691       "</b></p>\r\n"
1692       "<p>Please "
1693       "<a href=\"http://sourceforge.net/tracker/?group_id=11118&atid=111118\">"
1694       "file a bug report</a>.</p>\r\n"
1695       "</body>\r\n"
1696       "</html>\r\n";
1697    char errnumbuf[30];
1698    assert(csp);
1699    assert(rsp);
1700
1701    /* Reset rsp, if needed */
1702    freez(rsp->status);
1703    freez(rsp->head);
1704    freez(rsp->body);
1705    rsp->content_length = 0;
1706    rsp->head_length = 0;
1707    rsp->is_static = 0;
1708
1709    snprintf(errnumbuf, sizeof(errnumbuf), "%d", error_to_report);
1710
1711    rsp->body = malloc(strlen(body_prefix) + strlen(errnumbuf) + strlen(body_suffix) + 1);
1712    if (rsp->body == NULL)
1713    {
1714       return JB_ERR_MEMORY;
1715    }
1716    strcpy(rsp->body, body_prefix);
1717    strcat(rsp->body, errnumbuf);
1718    strcat(rsp->body, body_suffix);
1719
1720    rsp->status = strdup(status);
1721    if (rsp->status == NULL)
1722    {
1723       return JB_ERR_MEMORY;
1724    }
1725
1726    return JB_ERR_OK;
1727 }
1728
1729
1730 /*********************************************************************
1731  *
1732  * Function    :  cgi_error_bad_param
1733  *
1734  * Description :  CGI function that is called if the parameters
1735  *                (query string) for a CGI were wrong.
1736  *               
1737  * Parameters  :
1738  *          1  :  csp = Current client state (buffers, headers, etc...)
1739  *          2  :  rsp = http_response data structure for output
1740  *
1741  * CGI Parameters : none
1742  *
1743  * Returns     :  JB_ERR_OK on success
1744  *                JB_ERR_MEMORY on out-of-memory error.  
1745  *
1746  *********************************************************************/
1747 jb_err cgi_error_bad_param(struct client_state *csp,
1748                            struct http_response *rsp)
1749 {
1750    struct map *exports;
1751
1752    assert(csp);
1753    assert(rsp);
1754
1755    if (NULL == (exports = default_exports(csp, NULL)))
1756    {
1757       return JB_ERR_MEMORY;
1758    }
1759
1760    return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1761 }
1762
1763
1764 /*********************************************************************
1765  *
1766  * Function    :  cgi_redirect 
1767  *
1768  * Description :  CGI support function to generate a HTTP redirect
1769  *                message
1770  *
1771  * Parameters  :
1772  *          1  :  rsp = http_response data structure for output
1773  *          2  :  target = string with the target URL
1774  *
1775  * CGI Parameters : None
1776  *
1777  * Returns     :  JB_ERR_OK on success
1778  *                JB_ERR_MEMORY on out-of-memory error.  
1779  *
1780  *********************************************************************/
1781 jb_err cgi_redirect (struct http_response * rsp, const char *target)
1782 {
1783    jb_err err;
1784
1785    assert(rsp);
1786    assert(target);
1787
1788    err = enlist_unique_header(rsp->headers, "Location", target);
1789
1790    rsp->status = strdup("302 Local Redirect from Privoxy");
1791    if (rsp->status == NULL)
1792    {
1793       return JB_ERR_MEMORY;
1794    }
1795
1796    return err;
1797 }
1798
1799
1800 /*********************************************************************
1801  *
1802  * Function    :  add_help_link
1803  *
1804  * Description :  Produce a copy of the string given as item,
1805  *                embedded in an HTML link to its corresponding
1806  *                section (item name in uppercase) in the actions
1807  *                chapter of the user manual, (whose URL is given in
1808  *                the config and defaults to our web site).
1809  *
1810  *                FIXME: I currently only work for actions, and would
1811  *                       like to be generalized for other topics.
1812  *
1813  * Parameters  :  
1814  *          1  :  item = item (will NOT be free()d.) 
1815  *                       It is assumed to be HTML-safe.
1816  *          2  :  config = The current configuration.
1817  *
1818  * Returns     :  String with item embedded in link, or NULL on
1819  *                out-of-memory
1820  *
1821  *********************************************************************/
1822 char *add_help_link(const char *item,
1823                     struct configuration_spec *config)
1824 {
1825    char *result;
1826
1827    if (!item) return NULL;
1828
1829    result = strdup("<a href=\"");
1830    if (!strncmpic(config->usermanual, "file://", 7) ||
1831        !strncmpic(config->usermanual, "http", 4))
1832    {
1833       string_append(&result, config->usermanual);
1834    }
1835    else
1836    {
1837       string_append(&result, "http://");
1838       string_append(&result, CGI_SITE_2_HOST);
1839       string_append(&result, "/user-manual/");
1840    }
1841    string_append(&result, ACTIONS_HELP_PREFIX);
1842    string_join  (&result, string_toupper(item));
1843    string_append(&result, "\">");
1844    string_append(&result, item);
1845    string_append(&result, "</a> ");
1846
1847    return result;
1848 }
1849
1850
1851 /*********************************************************************
1852  *
1853  * Function    :  get_http_time
1854  *
1855  * Description :  Get the time in a format suitable for use in a
1856  *                HTTP header - e.g.:
1857  *                "Sun, 06 Nov 1994 08:49:37 GMT"
1858  *
1859  * Parameters  :  
1860  *          1  :  time_offset = Time returned will be current time
1861  *                              plus this number of seconds.
1862  *          2  :  buf = Destination for result.  Must be long enough
1863  *                      to hold 29 characters plus a trailing zero.
1864  *
1865  * Returns     :  N/A
1866  *
1867  *********************************************************************/
1868 void get_http_time(int time_offset, char *buf)
1869 {
1870    static const char day_names[7][4] =
1871       { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
1872    static const char month_names[12][4] =
1873       { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1874         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
1875
1876    struct tm *t;
1877    time_t current_time;
1878 #if defined(HAVE_GMTIME_R)
1879    /*
1880     * Declare dummy up here (instead of inside get/set gmt block) so it
1881     * doesn't go out of scope before it's potentially used in snprintf later.
1882     * Wrapping declaration inside HAVE_GMTIME_R keeps the compiler quiet when
1883     * !defined HAVE_GMTIME_R.
1884     */
1885    struct tm dummy; 
1886 #endif
1887
1888    assert(buf);
1889
1890    time(&current_time); /* get current time */
1891
1892    current_time += time_offset;
1893
1894    /* get and save the gmt */
1895    {
1896 #if HAVE_GMTIME_R
1897       t = gmtime_r(&current_time, &dummy);
1898 #elif FEATURE_PTHREAD
1899       pthread_mutex_lock(&gmtime_mutex);
1900       t = gmtime(&current_time);
1901       pthread_mutex_unlock(&gmtime_mutex);
1902 #else
1903       t = gmtime(&current_time);
1904 #endif
1905    }
1906
1907    /* Format: "Sun, 06 Nov 1994 08:49:37 GMT" */
1908    snprintf(buf, 30,
1909       "%s, %02d %s %4d %02d:%02d:%02d GMT",
1910       day_names[t->tm_wday],
1911       t->tm_mday,
1912       month_names[t->tm_mon],
1913       t->tm_year + 1900,
1914       t->tm_hour,
1915       t->tm_min,
1916       t->tm_sec
1917       );
1918
1919 }
1920
1921
1922 /*********************************************************************
1923  *
1924  * Function    :  finish_http_response
1925  *
1926  * Description :  Fill in the missing headers in an http response,
1927  *                and flatten the headers to an http head.
1928  *                For HEAD requests the body is freed once
1929  *                the Content-Length header is set.
1930  *
1931  * Parameters  :
1932  *          1  :  rsp = pointer to http_response to be processed
1933  *
1934  * Returns     :  A http_response, usually the rsp parameter.
1935  *                On error, free()s rsp and returns cgi_error_memory()
1936  *
1937  *********************************************************************/
1938 struct http_response *finish_http_response(const struct client_state *csp, struct http_response *rsp)
1939 {
1940    char buf[BUFFER_SIZE];
1941    jb_err err;
1942
1943    /* Special case - do NOT change this statically allocated response,
1944     * which is ready for output anyway.
1945     */
1946    if (rsp == cgi_error_memory_response)
1947    {
1948       return rsp;
1949    }
1950
1951    /* 
1952     * Fill in the HTTP Status
1953     */
1954    snprintf(buf, sizeof(buf), "HTTP/1.0 %s", rsp->status ? rsp->status : "200 OK");
1955    err = enlist_first(rsp->headers, buf);
1956
1957    /* 
1958     * Set the Content-Length
1959     */
1960    if (rsp->content_length == 0)
1961    {
1962       rsp->content_length = rsp->body ? strlen(rsp->body) : 0;
1963    }
1964    if (!err)
1965    {
1966       snprintf(buf, sizeof(buf), "Content-Length: %d", (int)rsp->content_length);
1967       err = enlist(rsp->headers, buf);
1968    }
1969
1970    if (0 == strcmpic(csp->http->gpc, "head"))
1971    {
1972       /*
1973        * The client only asked for the head. Dispose
1974        * the body and log an offensive message.
1975        *
1976        * While it may seem to be a bit inefficient to
1977        * prepare the body if it isn't needed, it's the
1978        * only way to get the Content-Length right for
1979        * dynamic pages. We could have disposed the body
1980        * earlier, but not without duplicating the
1981        * Content-Length setting code above.
1982        */
1983       log_error(LOG_LEVEL_CGI, "Preparing to give head to %s.", csp->ip_addr_str);
1984       freez(rsp->body);
1985       rsp->content_length = 0;
1986    }
1987
1988    if ((rsp->status != NULL) && strncmpic(rsp->status, "302", 3))
1989    {
1990      /*
1991       * If it's not a redirect without any content,
1992       * set the Content-Type to text/html if it's
1993       * not already specified.
1994       */
1995      if (!err) err = enlist_unique(rsp->headers, "Content-Type: text/html", 13);
1996    }
1997
1998    /*
1999     * Fill in the rest of the default headers:
2000     *
2001     * Date: set to current date/time.
2002     * Last-Modified: set to date/time the page was last changed.
2003     * Expires: set to date/time page next needs reloading.
2004     * Cache-Control: set to "no-cache" if applicable.
2005     * 
2006     * See http://www.w3.org/Protocols/rfc2068/rfc2068
2007     */
2008    if (rsp->is_static)
2009    {
2010       /*
2011        * Set Expires to about 10 min into the future so it'll get reloaded
2012        * occasionally, e.g. if Privoxy gets upgraded.
2013        */
2014
2015       if (!err)
2016       {
2017          get_http_time(0, buf);
2018          err = enlist_unique_header(rsp->headers, "Date", buf);
2019       }
2020
2021       /* Some date in the past. */
2022       if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Sat, 17 Jun 2000 12:00:00 GMT");
2023
2024       if (!err)
2025       {
2026          get_http_time(10 * 60, buf); /* 10 * 60sec = 10 minutes */
2027          err = enlist_unique_header(rsp->headers, "Expires", buf);
2028       }
2029    }
2030    else if (!strncmpic(rsp->status, "302", 3))
2031    {
2032       get_http_time(0, buf);
2033       if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
2034    }
2035    else
2036    {
2037       /*
2038        * Setting "Cache-Control" to "no-cache" and  "Expires" to
2039        * the current time doesn't exactly forbid caching, it just
2040        * requires the client to revalidate the cached copy.
2041        *
2042        * If a temporary problem occurs and the user tries again after
2043        * getting Privoxy's error message, a compliant browser may set the
2044        * If-Modified-Since header with the content of the error page's
2045        * Last-Modified header. More often than not, the document on the server
2046        * is older than Privoxy's error message, the server would send status code
2047        * 304 and the browser would display the outdated error message again and again.
2048        *
2049        * For documents delivered with status code 404 or 503 we set "Last-Modified"
2050        * to Tim Berners-Lee's birthday, which predates the age of any page on the web
2051        * and can be safely used to "revalidate" without getting a status code 304.
2052        *
2053        * There is no need to let the useless If-Modified-Since header reach the
2054        * server, it is therefore stripped by client_if_modified_since in parsers.c.
2055        */
2056       if (!err) err = enlist_unique_header(rsp->headers, "Cache-Control", "no-cache");
2057
2058       get_http_time(0, buf);
2059       if (!err) err = enlist_unique_header(rsp->headers, "Date", buf);
2060       if (!strncmpic(rsp->status, "404", 3) || !strncmpic(rsp->status, "503", 3))
2061       {
2062          if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", "Wed, 08 Jun 1955 12:00:00 GMT");
2063       }
2064       else
2065       {
2066          if (!err) err = enlist_unique_header(rsp->headers, "Last-Modified", buf);
2067       }
2068       if (!err) err = enlist_unique_header(rsp->headers, "Expires", "Sat, 17 Jun 2000 12:00:00 GMT");
2069       if (!err) err = enlist_unique_header(rsp->headers, "Pragma", "no-cache");
2070    }
2071
2072    /*
2073     * Quoting RFC 2616:
2074     *
2075     * HTTP/1.1 applications that do not support persistent connections MUST
2076     * include the "close" connection option in every message.
2077     */
2078    if (!err) err = enlist_unique_header(rsp->headers, "Connection", "close");
2079
2080    /* 
2081     * Write the head
2082     */
2083    if (err || (NULL == (rsp->head = list_to_text(rsp->headers))))
2084    {
2085       free_http_response(rsp);
2086       return cgi_error_memory();
2087    }
2088    rsp->head_length = strlen(rsp->head);
2089
2090    return rsp;
2091
2092 }
2093
2094
2095 /*********************************************************************
2096  *
2097  * Function    :  alloc_http_response
2098  *
2099  * Description :  Allocates a new http_response structure.
2100  *
2101  * Parameters  :  N/A
2102  *
2103  * Returns     :  pointer to a new http_response, or NULL.
2104  *
2105  *********************************************************************/
2106 struct http_response *alloc_http_response(void)
2107 {
2108    return (struct http_response *) zalloc(sizeof(struct http_response));
2109
2110 }
2111
2112
2113 /*********************************************************************
2114  *
2115  * Function    :  free_http_response
2116  *
2117  * Description :  Free the memory occupied by an http_response
2118  *                and its depandant structures.
2119  *
2120  * Parameters  :
2121  *          1  :  rsp = pointer to http_response to be freed
2122  *
2123  * Returns     :  N/A
2124  *
2125  *********************************************************************/
2126 void free_http_response(struct http_response *rsp)
2127 {
2128    /*
2129     * Must special case cgi_error_memory_response, which is never freed.
2130     */
2131    if (rsp && (rsp != cgi_error_memory_response))
2132    {
2133       freez(rsp->status);
2134       freez(rsp->head);
2135       freez(rsp->body);
2136       destroy_list(rsp->headers);
2137       free(rsp);
2138    }
2139
2140 }
2141
2142
2143 /*********************************************************************
2144  *
2145  * Function    :  template_load
2146  *
2147  * Description :  CGI support function that loads a given HTML
2148  *                template, ignoring comment lines and following
2149  *                #include statements up to a depth of 1.
2150  *
2151  * Parameters  :
2152  *          1  :  csp = Current client state (buffers, headers, etc...)
2153  *          2  :  template_ptr = Destination for pointer to loaded
2154  *                               template text.
2155  *          3  :  templatename = name of the HTML template to be used
2156  *          4  :  recursive = Flag set if this function calls itself
2157  *                            following an #include statament
2158  *
2159  * Returns     :  JB_ERR_OK on success
2160  *                JB_ERR_MEMORY on out-of-memory error.  
2161  *                JB_ERR_FILE if the template file cannot be read
2162  *
2163  *********************************************************************/
2164 jb_err template_load(struct client_state *csp, char **template_ptr, 
2165                      const char *templatename, int recursive)
2166 {
2167    jb_err err;
2168    char *templates_dir_path;
2169    char *full_path;
2170    char *file_buffer;
2171    char *included_module;
2172    const char *p;
2173    FILE *fp;
2174    char buf[BUFFER_SIZE];
2175
2176    assert(csp);
2177    assert(template_ptr);
2178    assert(templatename);
2179
2180    *template_ptr = NULL;
2181
2182    /* Validate template name.  Paranoia. */
2183    for (p = templatename; *p != 0; p++)
2184    {
2185       if ( ((*p < 'a') || (*p > 'z'))
2186         && ((*p < 'A') || (*p > 'Z'))
2187         && ((*p < '0') || (*p > '9'))
2188         && (*p != '-')
2189         && (*p != '.'))
2190       {
2191          /* Illegal character */
2192          return JB_ERR_FILE;
2193       }
2194    }
2195
2196    /*
2197     * Generate full path using either templdir
2198     * or confdir/templates as base directory.
2199     */
2200    if (NULL != csp->config->templdir)
2201    {
2202       templates_dir_path = strdup(csp->config->templdir);
2203    }
2204    else
2205    {
2206       templates_dir_path = make_path(csp->config->confdir, "templates");
2207    }
2208
2209    if (templates_dir_path == NULL)
2210    {
2211       log_error(LOG_LEVEL_ERROR, "Out of memory while generating template path for %s.",
2212          templatename);
2213       return JB_ERR_MEMORY;
2214    }
2215
2216    full_path = make_path(templates_dir_path, templatename);
2217    free(templates_dir_path);
2218    if (full_path == NULL)
2219    {
2220       log_error(LOG_LEVEL_ERROR, "Out of memory while generating full template path for %s.",
2221          templatename);
2222       return JB_ERR_MEMORY;
2223    }
2224
2225    /* Allocate buffer */
2226
2227    file_buffer = strdup("");
2228    if (file_buffer == NULL)
2229    {
2230       log_error(LOG_LEVEL_ERROR, "Not enough free memory to buffer %s.", full_path);
2231       free(full_path);
2232       return JB_ERR_MEMORY;
2233    }
2234
2235    /* Open template file */
2236
2237    if (NULL == (fp = fopen(full_path, "r")))
2238    {
2239       log_error(LOG_LEVEL_ERROR, "Cannot open template file %s: %E", full_path);
2240       free(full_path);
2241       free(file_buffer);
2242       return JB_ERR_FILE;
2243    }
2244    free(full_path);
2245
2246    /* 
2247     * Read the file, ignoring comments, and honoring #include
2248     * statements, unless we're already called recursively.
2249     *
2250     * FIXME: The comment handling could break with lines >BUFFER_SIZE long.
2251     *        This is unlikely in practise.
2252     */
2253    while (fgets(buf, BUFFER_SIZE, fp))
2254    {
2255       if (!recursive && !strncmp(buf, "#include ", 9))
2256       {
2257          if (JB_ERR_OK != (err = template_load(csp, &included_module, chomp(buf + 9), 1)))
2258          {
2259             free(file_buffer);
2260             fclose(fp);
2261             return err;
2262          }
2263
2264          if (string_join(&file_buffer, included_module))
2265          {
2266             fclose(fp);
2267             return JB_ERR_MEMORY;
2268          }
2269
2270          continue;
2271       }
2272
2273       /* skip lines starting with '#' */
2274       if (*buf == '#')
2275       {
2276          continue;
2277       }
2278
2279       if (string_append(&file_buffer, buf))
2280       {
2281          fclose(fp);
2282          return JB_ERR_MEMORY;
2283       }
2284    }
2285    fclose(fp);
2286
2287    *template_ptr = file_buffer;
2288
2289    return JB_ERR_OK;
2290 }
2291
2292
2293 /*********************************************************************
2294  *
2295  * Function    :  template_fill
2296  *
2297  * Description :  CGI support function that fills in a pre-loaded
2298  *                HTML template by replacing @name@ with value using
2299  *                pcrs, for each item in the output map.
2300  *
2301  *                Note that a leading '$' charachter in the export map's
2302  *                values will be stripped and toggle on backreference
2303  *                interpretation.
2304  *
2305  * Parameters  :
2306  *          1  :  template_ptr = IN: Template to be filled out.
2307  *                                   Will be free()d.
2308  *                               OUT: Filled out template.
2309  *                                    Caller must free().
2310  *          2  :  exports = map with fill in symbol -> name pairs
2311  *
2312  * Returns     :  JB_ERR_OK on success (and for uncritical errors)
2313  *                JB_ERR_MEMORY on out-of-memory error
2314  *
2315  *********************************************************************/
2316 jb_err template_fill(char **template_ptr, const struct map *exports)
2317 {
2318    struct map_entry *m;
2319    pcrs_job *job;
2320    char buf[BUFFER_SIZE];
2321    char *tmp_out_buffer;
2322    char *file_buffer;
2323    size_t  size;
2324    int error;
2325    const char *flags;
2326
2327    assert(template_ptr);
2328    assert(*template_ptr);
2329    assert(exports);
2330
2331    file_buffer = *template_ptr;
2332    size = strlen(file_buffer) + 1;
2333
2334    /* 
2335     * Assemble pcrs joblist from exports map
2336     */
2337    for (m = exports->first; m != NULL; m = m->next)
2338    {
2339       if (*m->name == '$')
2340       {
2341          /*
2342           * First character of name is '$', so remove this flag
2343           * character and allow backreferences ($1 etc) in the
2344           * "replace with" text.
2345           */
2346          snprintf(buf, BUFFER_SIZE, "%s", m->name + 1);
2347          flags = "sigU";
2348       }
2349       else
2350       {
2351          /*
2352           * Treat the "replace with" text as a literal string - 
2353           * no quoting needed, no backreferences allowed.
2354           * ("Trivial" ['T'] flag).
2355           */
2356          flags = "sigTU";
2357
2358          /* Enclose name in @@ */
2359          snprintf(buf, BUFFER_SIZE, "@%s@", m->name);
2360       }
2361
2362
2363       log_error(LOG_LEVEL_CGI, "Substituting: s/%s/%s/%s", buf, m->value, flags);
2364
2365       /* Make and run job. */
2366       job = pcrs_compile(buf, m->value, flags,  &error);
2367       if (job == NULL) 
2368       {
2369          if (error == PCRS_ERR_NOMEM)
2370          {
2371             free(file_buffer);
2372             *template_ptr = NULL;
2373             return JB_ERR_MEMORY;
2374          }
2375          else
2376          {
2377             log_error(LOG_LEVEL_ERROR, "Error compiling template fill job %s: %d", m->name, error);
2378             /* Hope it wasn't important and silently ignore the invalid job */
2379          }
2380       }
2381       else
2382       {
2383          error = pcrs_execute(job, file_buffer, size, &tmp_out_buffer, &size);
2384
2385          pcrs_free_job(job);
2386          if (NULL == tmp_out_buffer)
2387          {
2388             *template_ptr = NULL;
2389             return JB_ERR_MEMORY;
2390          }
2391
2392          if (error < 0)
2393          {
2394             /* 
2395              * Substitution failed, keep the original buffer,
2396              * log the problem and ignore it.
2397              * 
2398              * The user might see some unresolved @CGI_VARIABLES@,
2399              * but returning a special CGI error page seems unreasonable
2400              * and could mask more important error messages.
2401              */
2402             free(tmp_out_buffer);
2403             log_error(LOG_LEVEL_ERROR, "Failed to execute s/%s/%s/%s. %s",
2404                buf, m->value, flags, pcrs_strerror(error));
2405          }
2406          else
2407          {
2408             /* Substitution succeeded, use modified buffer. */
2409             free(file_buffer);
2410             file_buffer = tmp_out_buffer;
2411          }
2412       }
2413    }
2414
2415    /*
2416     * Return
2417     */
2418    *template_ptr = file_buffer;
2419    return JB_ERR_OK;
2420 }
2421
2422
2423 /*********************************************************************
2424  *
2425  * Function    :  template_fill_for_cgi
2426  *
2427  * Description :  CGI support function that loads a HTML template
2428  *                and fills it in.  Handles file-not-found errors
2429  *                by sending a HTML error message.  For convenience,
2430  *                this function also frees the passed "exports" map.
2431  *
2432  * Parameters  :
2433  *          1  :  csp = Client state
2434  *          2  :  templatename = name of the HTML template to be used
2435  *          3  :  exports = map with fill in symbol -> name pairs.
2436  *                          Will be freed by this function.
2437  *          4  :  rsp = Response structure to fill in.
2438  *
2439  * Returns     :  JB_ERR_OK on success
2440  *                JB_ERR_MEMORY on out-of-memory error
2441  *
2442  *********************************************************************/
2443 jb_err template_fill_for_cgi(struct client_state *csp,
2444                              const char *templatename,
2445                              struct map *exports,
2446                              struct http_response *rsp)
2447 {
2448    jb_err err;
2449    
2450    assert(csp);
2451    assert(templatename);
2452    assert(exports);
2453    assert(rsp);
2454
2455    err = template_load(csp, &rsp->body, templatename, 0);
2456    if (err == JB_ERR_FILE)
2457    {
2458       free_map(exports);
2459       return cgi_error_no_template(csp, rsp, templatename);
2460    }
2461    else if (err)
2462    {
2463       free_map(exports);
2464       return err; /* JB_ERR_MEMORY */
2465    }
2466    err = template_fill(&rsp->body, exports);
2467    free_map(exports);
2468    return err;
2469 }
2470
2471
2472 /*********************************************************************
2473  *
2474  * Function    :  default_exports
2475  *
2476  * Description :  returns a struct map list that contains exports
2477  *                which are common to all CGI functions.
2478  *
2479  * Parameters  :
2480  *          1  :  csp = Current client state (buffers, headers, etc...)
2481  *          2  :  caller = name of CGI who calls us and which should
2482  *                         be excluded from the generated menu. May be
2483  *                         NULL.
2484  * Returns     :  NULL if no memory, else a new map.  Caller frees.
2485  *
2486  *********************************************************************/
2487 struct map *default_exports(const struct client_state *csp, const char *caller)
2488 {
2489    char buf[20];
2490    jb_err err;
2491    struct map * exports;
2492    int local_help_exists = 0;
2493
2494    assert(csp);
2495
2496    exports = new_map();
2497    if (exports == NULL)
2498    {
2499       return NULL;
2500    }
2501
2502    err = map(exports, "version", 1, html_encode(VERSION), 0);
2503    if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
2504    if (!err) err = map(exports, "my-hostname",   1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
2505    if (!err) err = map(exports, "homepage",      1, html_encode(HOME_PAGE_URL), 0);
2506    if (!err) err = map(exports, "default-cgi",   1, html_encode(CGI_PREFIX), 0);
2507    if (!err) err = map(exports, "menu",          1, make_menu(caller, csp->config->feature_flags), 0);
2508    if (!err) err = map(exports, "code-status",   1, CODE_STATUS, 1);
2509    if (!strncmpic(csp->config->usermanual, "file://", 7) ||
2510        !strncmpic(csp->config->usermanual, "http", 4))
2511    {
2512       /* Manual is located somewhere else, just link to it. */
2513       if (!err) err = map(exports, "user-manual", 1, html_encode(csp->config->usermanual), 0);
2514    }
2515    else
2516    {
2517       /* Manual is delivered by Privoxy. */
2518       if (!err) err = map(exports, "user-manual", 1, html_encode(CGI_PREFIX"user-manual/"), 0);
2519    }
2520    if (!err) err = map(exports, "actions-help-prefix", 1, ACTIONS_HELP_PREFIX ,1);
2521 #ifdef FEATURE_TOGGLE
2522    if (!err) err = map_conditional(exports, "enabled-display", global_toggle_state);
2523 #else
2524    if (!err) err = map_block_killer(exports, "can-toggle");
2525 #endif
2526
2527    snprintf(buf, 20, "%d", csp->config->hport);
2528    if (!err) err = map(exports, "my-port", 1, buf, 1);
2529
2530    if(!strcmp(CODE_STATUS, "stable"))
2531    {
2532       if (!err) err = map_block_killer(exports, "unstable");
2533    }
2534
2535    if (csp->config->admin_address != NULL)
2536    {
2537       if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
2538       local_help_exists = 1;
2539    }
2540    else
2541    {
2542       if (!err) err = map_block_killer(exports, "have-adminaddr-info");
2543    }
2544
2545    if (csp->config->proxy_info_url != NULL)
2546    {
2547       if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
2548       local_help_exists = 1;
2549    }
2550    else
2551    {
2552       if (!err) err = map_block_killer(exports, "have-proxy-info");
2553    }
2554
2555    if (local_help_exists == 0)
2556    {
2557       if (!err) err = map_block_killer(exports, "have-help-info");
2558    }
2559
2560    if (err)
2561    {
2562       free_map(exports);
2563       return NULL;
2564    }
2565
2566    return exports;
2567 }
2568
2569
2570 /*********************************************************************
2571  *
2572  * Function    :  map_block_killer
2573  *
2574  * Description :  Convenience function.
2575  *                Adds a "killer" for the conditional HTML-template
2576  *                block <name>, i.e. a substitution of the regex
2577  *                "if-<name>-start.*if-<name>-end" to the given
2578  *                export list.
2579  *
2580  * Parameters  :  
2581  *          1  :  exports = map to extend
2582  *          2  :  name = name of conditional block
2583  *
2584  * Returns     :  JB_ERR_OK on success
2585  *                JB_ERR_MEMORY on out-of-memory error.  
2586  *
2587  *********************************************************************/
2588 jb_err map_block_killer(struct map *exports, const char *name)
2589 {
2590    char buf[1000]; /* Will do, since the names are hardwired */
2591
2592    assert(exports);
2593    assert(name);
2594    assert(strlen(name) < 490);
2595
2596    snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
2597    return map(exports, buf, 1, "", 1);
2598 }
2599
2600
2601 /*********************************************************************
2602  *
2603  * Function    :  map_block_keep
2604  *
2605  * Description :  Convenience function.  Removes the markers used
2606  *                by map-block-killer, to save a few bytes.
2607  *                i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
2608  *
2609  * Parameters  :  
2610  *          1  :  exports = map to extend
2611  *          2  :  name = name of conditional block
2612  *
2613  * Returns     :  JB_ERR_OK on success
2614  *                JB_ERR_MEMORY on out-of-memory error.  
2615  *
2616  *********************************************************************/
2617 jb_err map_block_keep(struct map *exports, const char *name)
2618 {
2619    jb_err err;
2620    char buf[500]; /* Will do, since the names are hardwired */
2621
2622    assert(exports);
2623    assert(name);
2624    assert(strlen(name) < 490);
2625
2626    snprintf(buf, 500, "if-%s-start", name);
2627    err = map(exports, buf, 1, "", 1);
2628
2629    if (err)
2630    {
2631       return err;
2632    }
2633
2634    snprintf(buf, 500, "if-%s-end", name);
2635    return map(exports, buf, 1, "", 1);
2636 }
2637
2638
2639 /*********************************************************************
2640  *
2641  * Function    :  map_conditional
2642  *
2643  * Description :  Convenience function.
2644  *                Adds an "if-then-else" for the conditional HTML-template
2645  *                block <name>, i.e. a substitution of the form:
2646  *                @if-<name>-then@
2647  *                   True text
2648  *                @else-not-<name>@
2649  *                   False text
2650  *                @endif-<name>@
2651  *
2652  *                The control structure and one of the alternatives
2653  *                will be hidden.
2654  *
2655  * Parameters  :  
2656  *          1  :  exports = map to extend
2657  *          2  :  name = name of conditional block
2658  *          3  :  choose_first = nonzero for first, zero for second.
2659  *
2660  * Returns     :  JB_ERR_OK on success
2661  *                JB_ERR_MEMORY on out-of-memory error.  
2662  *
2663  *********************************************************************/
2664 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
2665 {
2666    char buf[1000]; /* Will do, since the names are hardwired */
2667    jb_err err;
2668
2669    assert(exports);
2670    assert(name);
2671    assert(strlen(name) < 480);
2672
2673    snprintf(buf, 1000, (choose_first
2674       ? "else-not-%s@.*@endif-%s"
2675       : "if-%s-then@.*@else-not-%s"),
2676       name, name);
2677
2678    err = map(exports, buf, 1, "", 1);
2679    if (err)
2680    {
2681       return err;
2682    }
2683
2684    snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
2685    return map(exports, buf, 1, "", 1);
2686 }
2687
2688
2689 /*********************************************************************
2690  *
2691  * Function    :  make_menu
2692  *
2693  * Description :  Returns an HTML-formatted menu of the available 
2694  *                unhidden CGIs, excluding the one given in <self>
2695  *                and the toggle CGI if toggling is disabled.
2696  *
2697  * Parameters  :
2698  *          1  :  self = name of CGI to leave out, can be NULL for
2699  *                complete listing.
2700  *          2  :  feature_flags = feature bitmap from csp->config
2701  *                
2702  *
2703  * Returns     :  menu string, or NULL on out-of-memory error.
2704  *
2705  *********************************************************************/
2706 char *make_menu(const char *self, const unsigned feature_flags)
2707 {
2708    const struct cgi_dispatcher *d;
2709    char *result = strdup("");
2710
2711    if (self == NULL)
2712    {
2713       self = "NO-SUCH-CGI!";
2714    }
2715
2716    /* List available unhidden CGI's and export as "other-cgis" */
2717    for (d = cgi_dispatchers; d->name; d++)
2718    {
2719
2720 #ifdef FEATURE_TOGGLE
2721       if (!(feature_flags & RUNTIME_FEATURE_CGI_TOGGLE) && !strcmp(d->name, "toggle"))
2722       {
2723          /*
2724           * Suppress the toggle link if remote toggling is disabled.
2725           */
2726          continue;
2727       }
2728 #endif /* def FEATURE_TOGGLE */
2729
2730       if (d->description && strcmp(d->name, self))
2731       {
2732          char *html_encoded_prefix;
2733
2734          string_append(&result, "<li><a href=\"");
2735          html_encoded_prefix = html_encode(CGI_PREFIX);
2736          if (html_encoded_prefix == NULL)
2737          {
2738             return NULL;  
2739          }
2740          else
2741          {
2742             string_append(&result, html_encoded_prefix);
2743             free(html_encoded_prefix);
2744          }
2745          string_append(&result, d->name);
2746          string_append(&result, "\">");
2747          string_append(&result, d->description);
2748          string_append(&result, "</a></li>\n");
2749       }
2750    }
2751
2752    return result;
2753 }
2754
2755
2756 /*********************************************************************
2757  *
2758  * Function    :  dump_map
2759  *
2760  * Description :  HTML-dump a map for debugging (as table)
2761  *
2762  * Parameters  :
2763  *          1  :  the_map = map to dump
2764  *
2765  * Returns     :  string with HTML
2766  *
2767  *********************************************************************/
2768 char *dump_map(const struct map *the_map)
2769 {
2770    struct map_entry *cur_entry;
2771    char *ret = strdup("");
2772
2773    string_append(&ret, "<table>\n");
2774
2775    for (cur_entry = the_map->first;
2776         (cur_entry != NULL) && (ret != NULL);
2777         cur_entry = cur_entry->next)
2778    {
2779       string_append(&ret, "<tr><td><b>");
2780       string_join  (&ret, html_encode(cur_entry->name));
2781       string_append(&ret, "</b></td><td>");
2782       string_join  (&ret, html_encode(cur_entry->value));
2783       string_append(&ret, "</td></tr>\n");
2784    }
2785
2786    string_append(&ret, "</table>\n");
2787    return ret;
2788 }
2789
2790
2791 /*
2792   Local Variables:
2793   tab-width: 3
2794   end:
2795 */