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