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