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