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