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