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