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