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