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