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