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