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