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