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