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