2ff7e605e924f5c78b77d4d6fb4cd161c26a9a9f
[privoxy.git] / cgi.c
1 const char cgi_rcs[] = "$Id: cgi.c,v 1.67 2002/04/30 12:02:07 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.67  2002/04/30 12:02:07  oes
42  *    Nit: updated a comment
43  *
44  *    Revision 1.66  2002/04/26 18:32:57  jongfoster
45  *    Fixing a memory leak on error
46  *
47  *    Revision 1.65  2002/04/26 12:53:51  oes
48  *     - New function add_help_link
49  *     - default_exports now exports links to the user manual
50  *       and a prefix for links into the config chapter
51  *
52  *    Revision 1.64  2002/04/24 02:17:21  oes
53  *     - Better descriptions for CGIs
54  *     - Hide edit-actions, more shortcuts
55  *     - Moved get_char_param, get_string_param and get_number_param here
56  *       from cgiedit.c
57  *
58  *    Revision 1.63  2002/04/15 19:06:43  jongfoster
59  *    Typos
60  *
61  *    Revision 1.62  2002/04/10 19:59:46  jongfoster
62  *    Fixes to #include in templates:
63  *    - Didn't close main file if loading an included template fails.
64  *    - I'm paranoid and want to disallow "#include /etc/passwd".
65  *
66  *    Revision 1.61  2002/04/10 13:37:48  oes
67  *    Made templates modular: template_load now recursive with max depth 1
68  *
69  *    Revision 1.60  2002/04/08 20:50:25  swa
70  *    fixed JB spelling
71  *
72  *    Revision 1.59  2002/04/05 15:51:51  oes
73  *     - added send-stylesheet CGI
74  *     - bugfix: error-pages now get correct request protocol
75  *     - fixed
76  *     - kludged CGI descriptions and menu not to break JS syntax
77  *
78  *    Revision 1.58  2002/03/29 03:33:13  david__schmidt
79  *    Fix Mac OSX compiler warnings
80  *
81  *    Revision 1.57  2002/03/26 22:29:54  swa
82  *    we have a new homepage!
83  *
84  *    Revision 1.56  2002/03/24 17:50:46  jongfoster
85  *    Fixing compile error if actions file editor disabled
86  *
87  *    Revision 1.55  2002/03/24 16:55:06  oes
88  *    Making GIF checkerboard transparent
89  *
90  *    Revision 1.54  2002/03/24 16:18:15  jongfoster
91  *    Removing old logo
92  *
93  *    Revision 1.53  2002/03/24 16:06:00  oes
94  *    Correct transparency for checkerboard PNG. Thanks, Magnus!
95  *
96  *    Revision 1.52  2002/03/24 15:23:33  jongfoster
97  *    Name changes
98  *
99  *    Revision 1.51  2002/03/24 13:25:43  swa
100  *    name change related issues
101  *
102  *    Revision 1.50  2002/03/16 23:54:06  jongfoster
103  *    Adding graceful termination feature, to help look for memory leaks.
104  *    If you enable this (which, by design, has to be done by hand
105  *    editing config.h) and then go to http://i.j.b/die, then the program
106  *    will exit cleanly after the *next* request.  It should free all the
107  *    memory that was used.
108  *
109  *    Revision 1.49  2002/03/13 00:27:04  jongfoster
110  *    Killing warnings
111  *
112  *    Revision 1.48  2002/03/08 17:47:07  jongfoster
113  *    Adding comments
114  *
115  *    Revision 1.47  2002/03/08 16:41:33  oes
116  *    Added GIF images again
117  *
118  *    Revision 1.46  2002/03/07 03:48:38  oes
119  *     - Changed built-in images from GIF to PNG
120  *       (with regard to Unisys patent issue)
121  *     - Added a 4x4 pattern PNG which is less intrusive
122  *       than the logo but also clearly marks the deleted banners
123  *
124  *    Revision 1.45  2002/03/06 22:54:35  jongfoster
125  *    Automated function-comment nitpicking.
126  *
127  *    Revision 1.44  2002/03/05 22:43:45  david__schmidt
128  *    - Better error reporting on OS/2
129  *    - Fix double-slash comment (oops)
130  *
131  *    Revision 1.43  2002/03/05 21:33:45  david__schmidt
132  *    - Re-enable OS/2 building after new parms were added
133  *    - Fix false out of memory report when resolving CGI templates when no IP
134  *      address is available of failed attempt (a la no such domain)
135  *
136  *    Revision 1.42  2002/01/21 00:33:20  jongfoster
137  *    Replacing strsav() with the safer string_append() or string_join().
138  *    Adding map_block_keep() to save a few bytes in the edit-actions-list HTML.
139  *    Adding missing html_encode() to error message generators.
140  *    Adding edit-actions-section-swap and many "shortcuts" to the list of CGIs.
141  *
142  *    Revision 1.41  2002/01/17 20:56:22  jongfoster
143  *    Replacing hard references to the URL of the config interface
144  *    with #defines from project.h
145  *
146  *    Revision 1.40  2002/01/09 14:26:46  oes
147  *    Added support for thread-safe gmtime_r call.
148  *
149  *    Revision 1.39  2001/11/16 00:48:13  jongfoster
150  *    Fixing a compiler warning
151  *
152  *    Revision 1.38  2001/11/13 00:31:21  jongfoster
153  *    - Adding new CGIs for use by non-JavaScript browsers:
154  *        edit-actions-url-form
155  *        edit-actions-add-url-form
156  *        edit-actions-remove-url-form
157  *    - Fixing make_menu()'s HTML generation - it now quotes the href parameter.
158  *    - Fixing || bug.
159  *
160  *    Revision 1.37  2001/11/01 14:28:47  david__schmidt
161  *    Show enablement/disablement status in almost all templates.
162  *    There is a little trickiness here: apparent recursive resolution of
163  *    @if-enabled-then@ caused the toggle template to show status out-of-phase with
164  *    the actual enablement status.  So a similar construct,
165  *    @if-enabled-display-then@, is used to resolve the status display on non-'toggle'
166  *    templates.
167  *
168  *    Revision 1.36  2001/10/26 17:33:27  oes
169  *    marginal bugfix
170  *
171  *    Revision 1.35  2001/10/23 21:48:19  jongfoster
172  *    Cleaning up error handling in CGI functions - they now send back
173  *    a HTML error page and should never cause a FATAL error.  (Fixes one
174  *    potential source of "denial of service" attacks).
175  *
176  *    CGI actions file editor that works and is actually useful.
177  *
178  *    Ability to toggle Junkbuster remotely using a CGI call.
179  *
180  *    You can turn off both the above features in the main configuration
181  *    file, e.g. if you are running a multi-user proxy.
182  *
183  *    Revision 1.34  2001/10/18 22:22:09  david__schmidt
184  *    Only show "Local support" on templates conditionally:
185  *      - if either 'admin-address' or 'proxy-info-url' are uncommented in config
186  *      - if not, no Local support section appears
187  *
188  *    Revision 1.33  2001/10/14 22:28:41  jongfoster
189  *    Fixing stupid typo.
190  *
191  *    Revision 1.32  2001/10/14 22:20:18  jongfoster
192  *    - Changes to CGI dispatching method to match CGI names exactly,
193  *      rather than doing a prefix match.
194  *    - No longer need to count the length of the CGI handler names by hand.
195  *    - Adding new handler for 404 error when disptching a CGI, if none of
196  *      the handlers match.
197  *    - Adding new handlers for CGI actionsfile editor.
198  *
199  *    Revision 1.31  2001/10/10 10:56:39  oes
200  *    Failiure to load template now fatal. Before, the user got a hard-to-understand assertion failure from cgi.c
201  *
202  *    Revision 1.30  2001/10/02 15:30:57  oes
203  *    Introduced show-request cgi
204  *
205  *    Revision 1.29  2001/09/20 15:47:44  steudten
206  *
207  *    Fix BUG: Modify int size to size_t size in fill_template()
208  *     - removes big trouble on machines where sizeof(int) != sizeof(size_t).
209  *
210  *    Revision 1.28  2001/09/19 18:00:37  oes
211  *     - Deletef time() FIXME (Can't fail under Linux either, if
212  *       the argument is guaranteed to be in out address space,
213  *       which it is.)
214  *     - Fixed comments
215  *     - Pointer notation cosmetics
216  *     - Fixed a minor bug in template_fill(): Failiure of
217  *       pcrs_execute() now secure.
218  *
219  *    Revision 1.27  2001/09/16 17:08:54  jongfoster
220  *    Moving simple CGI functions from cgi.c to new file cgisimple.c
221  *
222  *    Revision 1.26  2001/09/16 15:47:37  jongfoster
223  *    First version of CGI-based edit interface.  This is very much a
224  *    work-in-progress, and you can't actually use it to edit anything
225  *    yet.  You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
226  *    to have any effect.
227  *
228  *    Revision 1.25  2001/09/16 15:02:35  jongfoster
229  *    Adding i.j.b/robots.txt.
230  *    Inlining add_stats() since it's only ever called from one place.
231  *
232  *    Revision 1.24  2001/09/16 11:38:01  jongfoster
233  *    Splitting fill_template() into 2 functions:
234  *    template_load() loads the file
235  *    template_fill() performs the PCRS regexps.
236  *    This is because the CGI edit interface has a "table row"
237  *    template which is used many times in the page - this
238  *    change means it's only loaded from disk once.
239  *
240  *    Revision 1.23  2001/09/16 11:16:05  jongfoster
241  *    Better error handling in dispatch_cgi() and parse_cgi_parameters()
242  *
243  *    Revision 1.22  2001/09/16 11:00:10  jongfoster
244  *    New function alloc_http_response, for symmetry with free_http_response
245  *
246  *    Revision 1.21  2001/09/13 23:53:03  jongfoster
247  *    Support for both static and dynamically generated CGI pages.
248  *    Correctly setting Last-Modified: and Expires: HTTP headers.
249  *
250  *    Revision 1.20  2001/09/13 23:40:36  jongfoster
251  *    (Cosmetic only) Indentation correction
252  *
253  *    Revision 1.19  2001/09/13 23:31:25  jongfoster
254  *    Moving image data to cgi.c rather than cgi.h.
255  *
256  *    Revision 1.18  2001/08/05 16:06:20  jongfoster
257  *    Modifiying "struct map" so that there are now separate header and
258  *    "map_entry" structures.  This means that functions which modify a
259  *    map no longer need to return a pointer to the modified map.
260  *    Also, it no longer reverses the order of the entries (which may be
261  *    important with some advanced template substitutions).
262  *
263  *    Revision 1.17  2001/08/05 15:57:38  oes
264  *    Adapted finish_http_response to new list_to_text
265  *
266  *    Revision 1.16  2001/08/01 21:33:18  jongfoster
267  *    Changes to fill_template() that reduce memory usage without having
268  *    an impact on performance.  I also renamed some variables so as not
269  *    to clash with the C++ keywords "new" and "template".
270  *
271  *    Revision 1.15  2001/08/01 21:19:22  jongfoster
272  *    Moving file version information to a separate CGI page.
273  *
274  *    Revision 1.14  2001/08/01 00:19:03  jongfoster
275  *    New function: map_conditional() for an if-then-else syntax.
276  *    Changing to use new version of show_defines()
277  *
278  *    Revision 1.13  2001/07/30 22:08:36  jongfoster
279  *    Tidying up #defines:
280  *    - All feature #defines are now of the form FEATURE_xxx
281  *    - Permanently turned off WIN_GUI_EDIT
282  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
283  *
284  *    Revision 1.12  2001/07/29 18:47:05  jongfoster
285  *    Adding missing #include "loadcfg.h"
286  *
287  *    Revision 1.11  2001/07/18 17:24:37  oes
288  *    Changed to conform to new pcrs interface
289  *
290  *    Revision 1.10  2001/07/13 13:53:13  oes
291  *    Removed all #ifdef PCRS and related code
292  *
293  *    Revision 1.9  2001/06/29 21:45:41  oes
294  *    Indentation, CRLF->LF, Tab-> Space
295  *
296  *    Revision 1.8  2001/06/29 13:21:46  oes
297  *    - Cosmetics: renamed and reordered functions, variables,
298  *      texts, improved comments  etc
299  *
300  *    - Removed ij_untrusted_url() The relevant
301  *      info is now part of the "untrusted" page,
302  *      which is generated by filters.c:trust_url()
303  *
304  *    - Generators of content now call finish_http_response()
305  *      themselves, making jcc.c:chat() a little less
306  *      cluttered
307  *
308  *    - Removed obsolete "Pragma: no-cache" from our headers
309  *
310  *    - http_responses now know their head length
311  *
312  *    - fill_template now uses the new interface to pcrs, so that
313  *       - long jobs (like whole files) no longer have to be assembled
314  *         in a fixed size buffer
315  *       - the new T (trivial) option is used, and the replacement may
316  *         contain Perl syntax backrefs without confusing pcrs
317  *
318  *    - Introduced default_exports() which generates a set of exports
319  *      common to all CGIs and other content generators
320  *
321  *    - Introduced convenience function map_block_killer()
322  *
323  *    - Introduced convenience function make_menu()
324  *
325  *    - Introduced CGI-like function error_response() which generates
326  *      the "No such domain" and "Connect failed" messages using the
327  *      CGI platform
328  *
329  *    - cgi_show_url_info:
330  *      - adapted to new CGI features
331  *      - form and answers now generated from same template
332  *      - http:// prefix in URL now OK
333  *
334  *    - cgi_show_status:
335  *      - adapted to new CGI features
336  *      - no longer uses csp->init_proxy_args
337  *
338  *    - cgi_default:
339  *      - moved menu generation to make_menu()
340  *
341  *    - add_stats now writes single export map entries instead
342  *      of a fixed string
343  *
344  *    - Moved redirect_url() to filters.c
345  *
346  *    - Fixed mem leak in free_http_response(), map_block_killer(),
347  *
348  *    - Removed logentry from cancelled commit
349  *
350  *    Revision 1.7  2001/06/09 10:51:58  jongfoster
351  *    Changing "show URL info" handler to new style.
352  *    Changing BUFSIZ ==> BUFFER_SIZE
353  *
354  *    Revision 1.6  2001/06/07 23:05:19  jongfoster
355  *    Removing code related to old forward and ACL files.
356  *
357  *    Revision 1.5  2001/06/05 19:59:16  jongfoster
358  *    Fixing multiline character string (a GCC-only "feature"), and snprintf (it's _snprintf under VC++).
359  *
360  *    Revision 1.4  2001/06/04 10:41:52  swa
361  *    show version string of cgi.h and cgi.c
362  *
363  *    Revision 1.3  2001/06/03 19:12:16  oes
364  *    introduced new cgi handling
365  *
366  *    No revisions before 1.3
367  *
368  **********************************************************************/
369 \f
370
371 #include "config.h"
372
373 #include <stdio.h>
374 #include <sys/types.h>
375 #include <stdlib.h>
376 #include <ctype.h>
377 #include <string.h>
378 #include <limits.h>
379 #include <assert.h>
380
381 #ifdef _WIN32
382 #define snprintf _snprintf
383 #endif /* def _WIN32 */
384
385 #include "project.h"
386 #include "cgi.h"
387 #include "list.h"
388 #include "encode.h"
389 #include "ssplit.h"
390 #include "errlog.h"
391 #include "miscutil.h"
392 #include "cgisimple.h"
393 #ifdef FEATURE_CGI_EDIT_ACTIONS
394 #include "cgiedit.h"
395 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
396 #include "loadcfg.h"
397 /* loadcfg.h is for g_bToggleIJB only */
398
399 const char cgi_h_rcs[] = CGI_H_VERSION;
400
401 /*
402  * List of CGI functions: name, handler, description
403  * Note: Do NOT use single quotes in the description;
404  *       this will break the dynamic "blocked" template!
405  */
406 static const struct cgi_dispatcher cgi_dispatchers[] = {
407    { "",
408          cgi_default,
409          "Privoxy main page" },
410 #ifdef FEATURE_GRACEFUL_TERMINATION
411    { "die", 
412          cgi_die,  
413          "<b>Shut down</b> - <em class=\"warning\">Do not deploy this build in a production environment, "
414          "this is a one click Denial Of Service attack!!!</em>" }, 
415 #endif
416    { "show-status", 
417          cgi_show_status,  
418          "View & change the current configuration" }, 
419    { "show-version", 
420          cgi_show_version,  
421          "View the source code version numbers" }, 
422    { "show-request", 
423          cgi_show_request,  
424          "View the request headers." }, 
425    { "show-url-info",
426          cgi_show_url_info, 
427          "Look up which actions apply to a URL and why"  },
428 #ifdef FEATURE_CGI_EDIT_ACTIONS
429    { "toggle",
430          cgi_toggle, 
431          "Toggle Privoxy on or off" },
432
433    { "edit-actions", /* Edit the actions list */
434          cgi_edit_actions, 
435          NULL },
436    { "eaa", /* Shortcut for edit-actions-add-url-form */
437          cgi_edit_actions_add_url_form, 
438          NULL },
439    { "eau", /* Shortcut for edit-actions-url-form */
440          cgi_edit_actions_url_form, 
441          NULL },
442    { "ear", /* Shortcut for edit-actions-remove-url-form */
443          cgi_edit_actions_remove_url_form, 
444          NULL },
445    { "eafu", /* Shortcut for edit-actions-for-url */
446          cgi_edit_actions_for_url, 
447          NULL },
448    { "eas", /* Shortcut for edit-actions-submit */
449          cgi_edit_actions_submit, 
450          NULL },
451    { "easa", /* Shortcut for edit-actions-section-add */
452          cgi_edit_actions_section_add, 
453          NULL },
454    { "easr", /* Shortcut for edit-actions-section-remove */
455          cgi_edit_actions_section_remove, 
456          NULL },
457    { "eass", /* Shortcut for edit-actions-section-swap */
458          cgi_edit_actions_section_swap, 
459          NULL },
460    { "edit-actions-for-url",
461          cgi_edit_actions_for_url, 
462          NULL /* Edit the actions for (a) specified URL(s) */ },
463    { "edit-actions-list",
464          cgi_edit_actions_list, 
465          NULL /* Edit the actions list */ },
466    { "edit-actions-submit",
467          cgi_edit_actions_submit, 
468          NULL /* Change the actions for (a) specified URL(s) */ },
469    { "edit-actions-url",
470          cgi_edit_actions_url, 
471          NULL /* Change a URL pattern in the actionsfile */ },
472    { "edit-actions-url-form",
473          cgi_edit_actions_url_form, 
474          NULL /* Form to change a URL pattern in the actionsfile */ },
475    { "edit-actions-add-url",
476          cgi_edit_actions_add_url, 
477          NULL /* Add a URL pattern to the actionsfile */ },
478    { "edit-actions-add-url-form",
479          cgi_edit_actions_add_url_form, 
480          NULL /* Form to add a URL pattern to the actionsfile */ },
481    { "edit-actions-remove-url",
482          cgi_edit_actions_remove_url, 
483          NULL /* Remove a URL pattern from the actionsfile */ },
484    { "edit-actions-remove-url-form",
485          cgi_edit_actions_remove_url_form, 
486          NULL /* Form to remove a URL pattern from the actionsfile */ },
487    { "edit-actions-section-add",
488          cgi_edit_actions_section_add, 
489          NULL /* Remove a section from the actionsfile */ },
490    { "edit-actions-section-remove",
491          cgi_edit_actions_section_remove, 
492          NULL /* Remove a section from the actionsfile */ },
493    { "edit-actions-section-swap",
494          cgi_edit_actions_section_swap, 
495          NULL /* Swap two sections in the actionsfile */ },
496 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
497    { "robots.txt", 
498          cgi_robots_txt,  
499          NULL /* Sends a robots.txt file to tell robots to go away. */ }, 
500    { "send-banner",
501          cgi_send_banner, 
502          NULL /* Send a built-in image */ },
503    { "send-stylesheet",
504          cgi_send_stylesheet, 
505          NULL /* Send templates/cgi-style.css */ },
506    { "t",
507          cgi_transparent_image, 
508          NULL /* Send a transparent image (short name) */ },
509    { NULL, /* NULL Indicates end of list and default page */
510          cgi_error_404,
511          NULL /* Unknown CGI page */ }
512 };
513
514
515 /*
516  * Bulit-in images for ad replacement
517  *
518  * Hint: You can encode your own images like this:
519  * cat your-image | perl -e 'while (read STDIN, $c, 1) { printf("\\%.3o", unpack("C", $c)); }'
520  */
521
522 #ifdef FEATURE_NO_GIFS
523
524 /*
525  * Checkerboard pattern, as a PNG.
526  */
527 const char image_pattern_data[] =
528    "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104"
529    "\122\000\000\000\004\000\000\000\004\010\002\000\000\000\046"
530    "\223\011\051\000\000\000\006\142\113\107\104\000\310\000\310"
531    "\000\310\052\045\225\037\000\000\000\032\111\104\101\124\170"
532    "\332\143\070\161\342\304\377\377\377\041\044\003\234\165\342"
533    "\304\011\006\234\062\000\125\200\052\251\125\174\360\223\000"
534    "\000\000\000\111\105\116\104\256\102\140\202";
535
536 /*
537  * 1x1 transparant PNG.
538  */
539 const char image_blank_data[] =
540  "\211\120\116\107\015\012\032\012\000\000\000\015\111\110\104\122"
541  "\000\000\000\004\000\000\000\004\010\006\000\000\000\251\361\236"
542  "\176\000\000\000\007\164\111\115\105\007\322\003\013\020\073\070"
543  "\013\025\036\203\000\000\000\011\160\110\131\163\000\000\013\022"
544  "\000\000\013\022\001\322\335\176\374\000\000\000\004\147\101\115"
545  "\101\000\000\261\217\013\374\141\005\000\000\000\033\111\104\101"
546  "\124\170\332\143\070\161\342\304\207\377\377\377\347\302\150\006"
547  "\144\016\210\146\040\250\002\000\042\305\065\221\270\027\131\110"
548  "\000\000\000\000\111\105\116\104\256\102\140\202";
549 #else
550
551 /*
552  * Checkerboard pattern, as a GIF.
553  */
554 const char image_pattern_data[] =
555    "\107\111\106\070\071\141\004\000\004\000\200\000\000\310\310"
556    "\310\377\377\377\041\376\016\111\040\167\141\163\040\141\040"
557    "\142\141\156\156\145\162\000\041\371\004\001\012\000\001\000"
558    "\054\000\000\000\000\004\000\004\000\000\002\005\104\174\147"
559    "\270\005\000\073";
560
561 /*
562  * 1x1 transparant GIF.
563  */
564 const char image_blank_data[] =
565    "GIF89a\001\000\001\000\200\000\000\377\377\377\000\000"
566    "\000!\371\004\001\000\000\000\000,\000\000\000\000\001"
567    "\000\001\000\000\002\002D\001\000;";
568 #endif
569
570 const size_t image_pattern_length = sizeof(image_pattern_data) - 1;
571 const size_t image_blank_length   = sizeof(image_blank_data) - 1;
572
573
574 static struct http_response cgi_error_memory_response[1];
575
576 static struct http_response *dispatch_known_cgi(struct client_state * csp,
577                                                 const char * path);
578 static struct map *parse_cgi_parameters(char *argstring);
579
580
581 /*********************************************************************
582  * 
583  * Function    :  dispatch_cgi
584  *
585  * Description :  Checks if a request URL has either the magical
586  *                hostname CGI_SITE_1_HOST (usually http://p.p/) or
587  *                matches CGI_SITE_2_HOST CGI_SITE_2_PATH (usually
588  *                http://config.privoxy.org/). If so, it passes
589  *                the (rest of the) path onto dispatch_known_cgi, which
590  *                calls the relevant CGI handler function.
591  *
592  * Parameters  :
593  *          1  :  csp = Current client state (buffers, headers, etc...)
594  *
595  * Returns     :  http_response if match, NULL if nonmatch or handler fail
596  *
597  *********************************************************************/
598 struct http_response *dispatch_cgi(struct client_state *csp)
599 {
600    const char *host = csp->http->host;
601    const char *path = csp->http->path;
602
603    /*
604     * Should we intercept ?
605     */
606
607    /* Note: "example.com" and "example.com." are equivalent hostnames. */
608
609    /* Either the host matches CGI_SITE_1_HOST ..*/
610    if (   ( (0 == strcmpic(host, CGI_SITE_1_HOST))
611          || (0 == strcmpic(host, CGI_SITE_1_HOST ".")))
612        && (path[0] == '/') )
613    {
614       /* ..then the path will all be for us.  Remove leading '/' */
615       path++;
616    }
617    /* Or it's the host part CGI_SITE_2_HOST, and the path CGI_SITE_2_PATH */
618    else if ( ( (0 == strcmpic(host, CGI_SITE_2_HOST ))
619             || (0 == strcmpic(host, CGI_SITE_2_HOST ".")) )
620           && (0 == strncmpic(path, CGI_SITE_2_PATH, strlen(CGI_SITE_2_PATH))) )
621    {
622       /* take everything following CGI_SITE_2_PATH */
623       path += strlen(CGI_SITE_2_PATH);
624       if (*path == '/')
625       {
626          /* skip the forward slash after CGI_SITE_2_PATH */
627          path++;
628       }
629       else if (*path != '\0')
630       {
631          /*
632           * wierdness: URL is /configXXX, where XXX is some string
633           * Do *NOT* intercept.
634           */
635          return NULL;
636       }
637    }
638    else
639    {
640       /* Not a CGI */
641       return NULL;
642    }
643
644    /* 
645     * This is a CGI call.
646     */
647
648    return dispatch_known_cgi(csp, path);
649 }
650
651
652 /*********************************************************************
653  * 
654  * Function    :  dispatch_known_cgi
655  *
656  * Description :  Processes a CGI once dispatch_cgi has determined that
657  *                it matches one of the magic prefixes. Parses the path
658  *                as a cgi name plus query string, prepares a map that
659  *                maps CGI parameter names to their values, initializes
660  *                the http_response struct, and calls the relevant CGI
661  *                handler function.
662  *
663  * Parameters  :
664  *          1  :  csp = Current client state (buffers, headers, etc...)
665  *          2  :  path = Path of CGI, with the CGI prefix removed.
666  *                       Should not have a leading "/".
667  *
668  * Returns     :  http_response, or NULL on handler failure or out of
669  *                memory.
670  *
671  *********************************************************************/
672 static struct http_response *dispatch_known_cgi(struct client_state * csp,
673                                                 const char * path)
674 {
675    const struct cgi_dispatcher *d;
676    struct map *param_list;
677    struct http_response *rsp;
678    char *query_args_start;
679    char *path_copy;
680    jb_err err;
681
682    if (NULL == (path_copy = strdup(path)))
683    {
684       return cgi_error_memory();
685    }
686
687    query_args_start = path_copy;
688    while (*query_args_start && *query_args_start != '?')
689    {
690       query_args_start++;
691    }
692    if (*query_args_start == '?')
693    {
694       *query_args_start++ = '\0';
695    }
696
697    if (NULL == (param_list = parse_cgi_parameters(query_args_start)))
698    {
699       free(path_copy);
700       return cgi_error_memory();
701    }
702
703
704    /*
705     * At this point:
706     * path_copy        = CGI call name
707     * param_list       = CGI params, as map
708     */
709
710    /* Get mem for response or fail*/
711    if (NULL == (rsp = alloc_http_response()))
712    {
713       free(path_copy);
714       free_map(param_list);
715       return cgi_error_memory();
716    }
717
718    log_error(LOG_LEVEL_GPC, "%s%s cgi call", csp->http->hostport, csp->http->path);
719    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", 
720                             csp->ip_addr_str, csp->http->cmd); 
721
722    /* Find and start the right CGI function*/
723    d = cgi_dispatchers;
724    for (;;)
725    {
726       if ((d->name == NULL) || (strcmp(path_copy, d->name) == 0))
727       {
728          err = (d->handler)(csp, rsp, param_list);
729          free(path_copy);
730          free_map(param_list);
731          if (err == JB_ERR_CGI_PARAMS)
732          {
733             err = cgi_error_bad_param(csp, rsp);
734          }
735          if (!err)
736          {
737             /* It worked */
738             return finish_http_response(rsp);
739          }
740          else
741          {
742             /* Error in handler, probably out-of-memory */
743             free_http_response(rsp);
744             return cgi_error_memory();
745          }
746       }
747       d++;
748    }
749 }
750
751
752 /*********************************************************************
753  *
754  * Function    :  parse_cgi_parameters
755  *
756  * Description :  Parse a URL-encoded argument string into name/value
757  *                pairs and store them in a struct map list.
758  *
759  * Parameters  :
760  *          1  :  argstring = string to be parsed.  Will be trashed.
761  *
762  * Returns     :  pointer to param list, or NULL if out of memory.
763  *
764  *********************************************************************/
765 static struct map *parse_cgi_parameters(char *argstring)
766 {
767    char *p;
768    char *vector[BUFFER_SIZE];
769    int pairs, i;
770    struct map *cgi_params;
771
772    if (NULL == (cgi_params = new_map()))
773    {
774       return NULL;
775    }
776
777    pairs = ssplit(argstring, "&", vector, SZ(vector), 1, 1);
778
779    for (i = 0; i < pairs; i++)
780    {
781       if ((NULL != (p = strchr(vector[i], '='))) && (*(p+1) != '\0'))
782       {
783          *p = '\0';
784          if (map(cgi_params, url_decode(vector[i]), 0, url_decode(++p), 0))
785          {
786             free_map(cgi_params);
787             return NULL;
788          }
789       }
790    }
791
792    return cgi_params;
793
794 }
795
796
797 /*********************************************************************
798  *
799  * Function    :  get_char_param
800  *
801  * Description :  Get a single-character parameter passed to a CGI
802  *                function.
803  *
804  * Parameters  :
805  *          1  :  parameters = map of cgi parameters
806  *          2  :  param_name = The name of the parameter to read
807  *
808  * Returns     :  Uppercase character on success, '\0' on error.
809  *
810  *********************************************************************/
811 char get_char_param(const struct map *parameters,
812                     const char *param_name)
813 {
814    char ch;
815
816    assert(parameters);
817    assert(param_name);
818
819    ch = *(lookup(parameters, param_name));
820    if ((ch >= 'a') && (ch <= 'z'))
821    {
822       ch = ch - 'a' + 'A';
823    }
824
825    return ch;
826 }
827
828
829 /*********************************************************************
830  *
831  * Function    :  get_string_param
832  *
833  * Description :  Get a string paramater, to be used as an
834  *                ACTION_STRING or ACTION_MULTI paramater.
835  *                Validates the input to prevent stupid/malicious
836  *                users from corrupting their action file.
837  *
838  * Parameters  :
839  *          1  :  parameters = map of cgi parameters
840  *          2  :  param_name = The name of the parameter to read
841  *          3  :  pparam = destination for paramater.  Allocated as
842  *                part of the map "parameters", so don't free it.
843  *                Set to NULL if not specified.
844  *
845  * Returns     :  JB_ERR_OK         on success, or if the paramater
846  *                                  was not specified.
847  *                JB_ERR_MEMORY     on out-of-memory.
848  *                JB_ERR_CGI_PARAMS if the paramater is not valid.
849  *
850  *********************************************************************/
851 jb_err get_string_param(const struct map *parameters,
852                         const char *param_name,
853                         const char **pparam)
854 {
855    const char *param;
856    const char *s;
857    char ch;
858
859    assert(parameters);
860    assert(param_name);
861    assert(pparam);
862
863    *pparam = NULL;
864
865    param = lookup(parameters, param_name);
866    if (!*param)
867    {
868       return JB_ERR_OK;
869    }
870
871    if (strlen(param) >= CGI_PARAM_LEN_MAX)
872    {
873       /*
874        * Too long.
875        *
876        * Note that the length limit is arbitrary, it just seems
877        * sensible to limit it to *something*.  There's no
878        * technical reason for any limit at all.
879        */
880       return JB_ERR_CGI_PARAMS;
881    }
882
883    /* Check every character to see if it's legal */
884    s = param;
885    while ((ch = *s++) != '\0')
886    {
887       if ( ((unsigned char)ch < (unsigned char)' ')
888         || (ch == '}') )
889       {
890          /* Probable hack attempt, or user accidentally used '}'. */
891          return JB_ERR_CGI_PARAMS;
892       }
893    }
894
895    /* Success */
896    *pparam = param;
897
898    return JB_ERR_OK;
899 }
900
901
902 /*********************************************************************
903  *
904  * Function    :  get_number_param
905  *
906  * Description :  Get a non-negative integer from the parameters
907  *                passed to a CGI function.
908  *
909  * Parameters  :
910  *          1  :  csp = Current client state (buffers, headers, etc...)
911  *          2  :  parameters = map of cgi parameters
912  *          3  :  name = Name of CGI parameter to read
913  *          4  :  pvalue = destination for value.
914  *                         Set to -1 on error.
915  *
916  * Returns     :  JB_ERR_OK         on success
917  *                JB_ERR_MEMORY     on out-of-memory
918  *                JB_ERR_CGI_PARAMS if the parameter was not specified
919  *                                  or is not valid.
920  *
921  *********************************************************************/
922 jb_err get_number_param(struct client_state *csp,
923                         const struct map *parameters,
924                         char *name,
925                         unsigned *pvalue)
926 {
927    const char *param;
928    char ch;
929    unsigned value;
930
931    assert(csp);
932    assert(parameters);
933    assert(name);
934    assert(pvalue);
935
936    *pvalue = 0; 
937
938    param = lookup(parameters, name);
939    if (!*param)
940    {
941       return JB_ERR_CGI_PARAMS;
942    }
943
944    /* We don't use atoi because I want to check this carefully... */
945
946    value = 0;
947    while ((ch = *param++) != '\0')
948    {
949       if ((ch < '0') || (ch > '9'))
950       {
951          return JB_ERR_CGI_PARAMS;
952       }
953
954       ch -= '0';
955
956       /* Note:
957        *
958        * <limits.h> defines UINT_MAX
959        *
960        * (UINT_MAX - ch) / 10 is the largest number that
961        *     can be safely multiplied by 10 then have ch added.
962        */
963       if (value > ((UINT_MAX - (unsigned)ch) / 10U))
964       {
965          return JB_ERR_CGI_PARAMS;
966       }
967
968       value = value * 10 + ch;
969    }
970
971    /* Success */
972    *pvalue = value;
973
974    return JB_ERR_OK;
975
976 }
977
978
979 /*********************************************************************
980  *
981  * Function    :  error_response
982  *
983  * Description :  returns an http_response that explains the reason
984  *                why a request failed.
985  *
986  * Parameters  :
987  *          1  :  csp = Current client state (buffers, headers, etc...)
988  *          2  :  templatename = Which template should be used for the answer
989  *          3  :  sys_err = system error number
990  *
991  * Returns     :  A http_response.  If we run out of memory, this
992  *                will be cgi_error_memory().
993  *
994  *********************************************************************/
995 struct http_response *error_response(struct client_state *csp,
996                                      const char *templatename,
997                                      int sys_err)
998 {
999    jb_err err;
1000    struct http_response *rsp;
1001    struct map * exports = default_exports(csp, NULL);
1002    if (exports == NULL)
1003    {
1004       return cgi_error_memory();
1005    }
1006
1007    if (NULL == (rsp = alloc_http_response()))
1008    {
1009       free_map(exports);
1010       return cgi_error_memory();
1011    }
1012
1013    err = map(exports, "host", 1, html_encode(csp->http->host), 0);
1014    if (!err) err = map(exports, "hostport", 1, html_encode(csp->http->hostport), 0);
1015    if (!err) err = map(exports, "path", 1, html_encode(csp->http->path), 0);
1016    if (!err) err = map(exports, "error", 1, html_encode_and_free_original(safe_strerror(sys_err)), 0);
1017    if (!err) err = map(exports, "protocol", 1, csp->http->ssl ? "https://" : "http://", 1); 
1018    if (!err)
1019    {
1020      err = map(exports, "host-ip", 1, html_encode(csp->http->host_ip_addr_str), 0);
1021      if (err)
1022      {
1023        /* Some failures, like "404 no such domain", don't have an IP address. */
1024        err = map(exports, "host-ip", 1, html_encode(csp->http->host), 0);
1025      }
1026    }
1027
1028
1029    if (err)
1030    {
1031       free_map(exports);
1032       free_http_response(rsp);
1033       return cgi_error_memory();
1034    }
1035
1036    if (!strcmp(templatename, "no-such-domain"))
1037    {
1038       rsp->status = strdup("404 No such domain");
1039       if (rsp->status == NULL)
1040       {
1041          free_map(exports);
1042          free_http_response(rsp);
1043          return cgi_error_memory();
1044       }
1045    }
1046    else if (!strcmp(templatename, "connect-failed"))
1047    {
1048       rsp->status = strdup("503 Connect failed");
1049       if (rsp->status == NULL)
1050       {
1051          free_map(exports);
1052          free_http_response(rsp);
1053          return cgi_error_memory();
1054       }
1055    }
1056
1057    err = template_fill_for_cgi(csp, templatename, exports, rsp);
1058    if (err)
1059    {
1060       free_http_response(rsp);
1061       return cgi_error_memory();
1062    }
1063
1064    return finish_http_response(rsp);
1065 }
1066
1067
1068 /*********************************************************************
1069  *
1070  * Function    :  cgi_init_error_messages
1071  *
1072  * Description :  Call at the start of the program to initialize
1073  *                the error message used by cgi_error_memory().
1074  *
1075  * Parameters  :  N/A
1076  *
1077  * Returns     :  N/A
1078  *
1079  *********************************************************************/
1080 void cgi_init_error_messages(void)
1081 {
1082    memset(cgi_error_memory_response, '\0', sizeof(*cgi_error_memory_response));
1083    cgi_error_memory_response->head =
1084       "HTTP/1.0 500 Internal Privoxy Error\r\n"
1085       "Content-Type: text/html\r\n"
1086       "\r\n";
1087    cgi_error_memory_response->body =
1088       "<html>\r\n"
1089       "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1090       "<body>\r\n"
1091       "<h1>500 Internal Privoxy Error</h1>\r\n"
1092       "<p>Privoxy <b>ran out of memory</b> while processing your request.</p>\r\n"
1093       "<p>Please contact your proxy administrator, or try again later</p>\r\n"
1094       "</body>\r\n"
1095       "</html>\r\n";
1096
1097    cgi_error_memory_response->head_length =
1098       strlen(cgi_error_memory_response->head);
1099    cgi_error_memory_response->content_length =
1100       strlen(cgi_error_memory_response->body);
1101 }
1102
1103
1104 /*********************************************************************
1105  *
1106  * Function    :  cgi_error_memory
1107  *
1108  * Description :  Called if a CGI function runs out of memory.
1109  *                Returns a statically-allocated error response.
1110  *
1111  * Parameters  :  N/A
1112  *
1113  * Returns     :  http_response data structure for output.  This is
1114  *                statically allocated, for obvious reasons.
1115  *
1116  *********************************************************************/
1117 struct http_response *cgi_error_memory(void)
1118 {
1119    /* assert that it's been initialized. */
1120    assert(cgi_error_memory_response->head);
1121
1122    return cgi_error_memory_response;
1123 }
1124
1125
1126 /*********************************************************************
1127  *
1128  * Function    :  cgi_error_no_template
1129  *
1130  * Description :  Almost-CGI function that is called if a templae
1131  *                cannot be loaded.  Note this is not a true CGI,
1132  *                it takes a template name rather than a map of 
1133  *                parameters.
1134  *
1135  * Parameters  :
1136  *          1  :  csp = Current client state (buffers, headers, etc...)
1137  *          2  :  rsp = http_response data structure for output
1138  *          3  :  template_name = Name of template that could not
1139  *                                be loaded.
1140  *
1141  * Returns     :  JB_ERR_OK on success
1142  *                JB_ERR_MEMORY on out-of-memory error.  
1143  *
1144  *********************************************************************/
1145 jb_err cgi_error_no_template(struct client_state *csp,
1146                              struct http_response *rsp,
1147                              const char *template_name)
1148 {
1149    static const char status[] =
1150       "500 Internal Privoxy Error";
1151    static const char body_prefix[] =
1152       "<html>\r\n"
1153       "<head><title>500 Internal Privoxy Error</title></head>\r\n"
1154       "<body>\r\n"
1155       "<h1>500 Internal Privoxy Error</h1>\r\n"
1156       "<p>Privoxy encountered an error while processing your request:</p>\r\n"
1157       "<p><b>Could not load template file <code>";
1158    static const char body_suffix[] =
1159       "</code> or one of it's included components.</b></p>\r\n"
1160       "<p>Please contact your proxy administrator.</p>\r\n"
1161       "<p>If you are the proxy administrator, please put the required file(s)"
1162       "in the <code><i>(confdir)</i>/templates</code> directory.  The "
1163       "location of the <code><i>(confdir)</i></code> directory "
1164       "is specified in the main Privoxy <code>config</code> "
1165       "file.  (It's typically the Privoxy install directory"
1166 #ifndef _WIN32
1167       ", or <code>/etc/privoxy/</code>"
1168 #endif /* ndef _WIN32 */
1169       ").</p>\r\n"
1170       "</body>\r\n"
1171       "</html>\r\n";
1172
1173    assert(csp);
1174    assert(rsp);
1175    assert(template_name);
1176
1177    /* Reset rsp, if needed */
1178    freez(rsp->status);
1179    freez(rsp->head);
1180    freez(rsp->body);
1181    rsp->content_length = 0;
1182    rsp->head_length = 0;
1183    rsp->is_static = 0;
1184
1185    rsp->body = malloc(strlen(body_prefix) + strlen(template_name) + strlen(body_suffix) + 1);
1186    if (rsp->body == NULL)
1187    {
1188       return JB_ERR_MEMORY;
1189    }
1190    strcpy(rsp->body, body_prefix);
1191    strcat(rsp->body, template_name);
1192    strcat(rsp->body, body_suffix);
1193
1194    rsp->status = strdup(status);
1195    if (rsp->body == NULL)
1196    {
1197       return JB_ERR_MEMORY;
1198    }
1199
1200    return JB_ERR_OK;
1201 }
1202
1203
1204 /*********************************************************************
1205  *
1206  * Function    :  cgi_error_bad_param
1207  *
1208  * Description :  CGI function that is called if the parameters
1209  *                (query string) for a CGI were wrong.
1210  *               
1211  * Parameters  :
1212  *          1  :  csp = Current client state (buffers, headers, etc...)
1213  *          2  :  rsp = http_response data structure for output
1214  *
1215  * CGI Parameters : none
1216  *
1217  * Returns     :  JB_ERR_OK on success
1218  *                JB_ERR_MEMORY on out-of-memory error.  
1219  *
1220  *********************************************************************/
1221 jb_err cgi_error_bad_param(struct client_state *csp,
1222                            struct http_response *rsp)
1223 {
1224    struct map *exports;
1225
1226    assert(csp);
1227    assert(rsp);
1228
1229    if (NULL == (exports = default_exports(csp, NULL)))
1230    {
1231       return JB_ERR_MEMORY;
1232    }
1233
1234    return template_fill_for_cgi(csp, "cgi-error-bad-param", exports, rsp);
1235 }
1236
1237
1238 /*********************************************************************
1239  *
1240  * Function    :  add_help_link
1241  *
1242  * Description :  Produce a copy of the string given as item,
1243  *                embedded in an HTML link to its corresponding
1244  *                section (item name in uppercase) in the configuration
1245  *                chapter of the user manual, (whose URL is given in
1246  *                the config and defaults to our web site).
1247  *
1248  * Parameters  :  
1249  *          1  :  item = item (will NOT be free()d.) 
1250  *                       It is assumed to be HTML-safe.
1251  *          2  :  config = The current configuration.
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  :  templatename = 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  *          4  :  rsp = Response structure to fill in.
1756  *
1757  * Returns     :  JB_ERR_OK on success
1758  *                JB_ERR_MEMORY on out-of-memory error
1759  *
1760  *********************************************************************/
1761 jb_err template_fill_for_cgi(struct client_state *csp,
1762                              const char *templatename,
1763                              struct map *exports,
1764                              struct http_response *rsp)
1765 {
1766    jb_err err;
1767    
1768    assert(csp);
1769    assert(templatename);
1770    assert(exports);
1771    assert(rsp);
1772
1773    err = template_load(csp, &rsp->body, templatename, 0);
1774    if (err == JB_ERR_FILE)
1775    {
1776       free_map(exports);
1777       return cgi_error_no_template(csp, rsp, templatename);
1778    }
1779    else if (err)
1780    {
1781       free_map(exports);
1782       return err; /* JB_ERR_MEMORY */
1783    }
1784    err = template_fill(&rsp->body, exports);
1785    free_map(exports);
1786    return err;
1787 }
1788
1789
1790 /*********************************************************************
1791  *
1792  * Function    :  default_exports
1793  *
1794  * Description :  returns a struct map list that contains exports
1795  *                which are common to all CGI functions.
1796  *
1797  * Parameters  :
1798  *          1  :  csp = Current client state (buffers, headers, etc...)
1799  *          2  :  caller = name of CGI who calls us and which should
1800  *                         be excluded from the generated menu. May be
1801  *                         NULL.
1802  * Returns     :  NULL if no memory, else a new map.  Caller frees.
1803  *
1804  *********************************************************************/
1805 struct map *default_exports(const struct client_state *csp, const char *caller)
1806 {
1807    char buf[20];
1808    jb_err err;
1809    struct map * exports;
1810    int local_help_exists = 0;
1811
1812    assert(csp);
1813
1814    exports = new_map();
1815    if (exports == NULL)
1816    {
1817       return NULL;
1818    }
1819
1820    err = map(exports, "version", 1, html_encode(VERSION), 0);
1821    if (!err) err = map(exports, "my-ip-address", 1, html_encode(csp->my_ip_addr_str ? csp->my_ip_addr_str : "unknown"), 0);
1822    if (!err) err = map(exports, "my-hostname",   1, html_encode(csp->my_hostname ? csp->my_hostname : "unknown"), 0);
1823    if (!err) err = map(exports, "homepage",      1, html_encode(HOME_PAGE_URL), 0);
1824    if (!err) err = map(exports, "default-cgi",   1, html_encode(CGI_PREFIX), 0);
1825    if (!err) err = map(exports, "menu",          1, make_menu(caller), 0);
1826    if (!err) err = map(exports, "code-status",   1, CODE_STATUS, 1);
1827    if (!err) err = map(exports, "user-manual",   1, csp->config->usermanual ,1);
1828    if (!err) err = map(exports, "helplink",      1, HELP_LINK_PREFIX ,1);
1829    if (!err) err = map_conditional(exports, "enabled-display", g_bToggleIJB);
1830
1831    snprintf(buf, 20, "%d", csp->config->hport);
1832    if (!err) err = map(exports, "my-port", 1, buf, 1);
1833
1834    if(!strcmp(CODE_STATUS, "stable"))
1835    {
1836       if (!err) err = map_block_killer(exports, "unstable");
1837    }
1838
1839    if (csp->config->admin_address != NULL)
1840    {
1841       if (!err) err = map(exports, "admin-address", 1, html_encode(csp->config->admin_address), 0);
1842       local_help_exists = 1;
1843    }
1844    else
1845    {
1846       if (!err) err = map_block_killer(exports, "have-adminaddr-info");
1847    }
1848
1849    if (csp->config->proxy_info_url != NULL)
1850    {
1851       if (!err) err = map(exports, "proxy-info-url", 1, html_encode(csp->config->proxy_info_url), 0);
1852       local_help_exists = 1;
1853    }
1854    else
1855    {
1856       if (!err) err = map_block_killer(exports, "have-proxy-info");
1857    }
1858
1859    if (local_help_exists == 0)
1860    {
1861       if (!err) err = map_block_killer(exports, "have-help-info");
1862    }
1863
1864    if (err)
1865    {
1866       free_map(exports);
1867       return NULL;
1868    }
1869
1870    return exports;
1871 }
1872
1873
1874 /*********************************************************************
1875  *
1876  * Function    :  map_block_killer
1877  *
1878  * Description :  Convenience function.
1879  *                Adds a "killer" for the conditional HTML-template
1880  *                block <name>, i.e. a substitution of the regex
1881  *                "if-<name>-start.*if-<name>-end" to the given
1882  *                export list.
1883  *
1884  * Parameters  :  
1885  *          1  :  exports = map to extend
1886  *          2  :  name = name of conditional block
1887  *
1888  * Returns     :  JB_ERR_OK on success
1889  *                JB_ERR_MEMORY on out-of-memory error.  
1890  *
1891  *********************************************************************/
1892 jb_err map_block_killer(struct map *exports, const char *name)
1893 {
1894    char buf[1000]; /* Will do, since the names are hardwired */
1895
1896    assert(exports);
1897    assert(name);
1898    assert(strlen(name) < 490);
1899
1900    snprintf(buf, 1000, "if-%s-start.*if-%s-end", name, name);
1901    return map(exports, buf, 1, "", 1);
1902 }
1903
1904
1905 /*********************************************************************
1906  *
1907  * Function    :  map_block_keep
1908  *
1909  * Description :  Convenience function.  Removes the markers used
1910  *                by map-block-killer, to save a few bytes.
1911  *                i.e. removes "@if-<name>-start@" and "@if-<name>-end@"
1912  *
1913  * Parameters  :  
1914  *          1  :  exports = map to extend
1915  *          2  :  name = name of conditional block
1916  *
1917  * Returns     :  JB_ERR_OK on success
1918  *                JB_ERR_MEMORY on out-of-memory error.  
1919  *
1920  *********************************************************************/
1921 jb_err map_block_keep(struct map *exports, const char *name)
1922 {
1923    jb_err err;
1924    char buf[500]; /* Will do, since the names are hardwired */
1925
1926    assert(exports);
1927    assert(name);
1928    assert(strlen(name) < 490);
1929
1930    snprintf(buf, 500, "if-%s-start", name);
1931    err = map(exports, buf, 1, "", 1);
1932
1933    if (err)
1934    {
1935       return err;
1936    }
1937
1938    snprintf(buf, 500, "if-%s-end", name);
1939    return map(exports, buf, 1, "", 1);
1940 }
1941
1942
1943 /*********************************************************************
1944  *
1945  * Function    :  map_conditional
1946  *
1947  * Description :  Convenience function.
1948  *                Adds an "if-then-else" for the conditional HTML-template
1949  *                block <name>, i.e. a substitution of the form:
1950  *                @if-<name>-then@
1951  *                   True text
1952  *                @else-not-<name>@
1953  *                   False text
1954  *                @endif-<name>@
1955  *
1956  *                The control structure and one of the alternatives
1957  *                will be hidden.
1958  *
1959  * Parameters  :  
1960  *          1  :  exports = map to extend
1961  *          2  :  name = name of conditional block
1962  *          3  :  choose_first = nonzero for first, zero for second.
1963  *
1964  * Returns     :  JB_ERR_OK on success
1965  *                JB_ERR_MEMORY on out-of-memory error.  
1966  *
1967  *********************************************************************/
1968 jb_err map_conditional(struct map *exports, const char *name, int choose_first)
1969 {
1970    char buf[1000]; /* Will do, since the names are hardwired */
1971    jb_err err;
1972
1973    assert(exports);
1974    assert(name);
1975    assert(strlen(name) < 480);
1976
1977    snprintf(buf, 1000, (choose_first
1978       ? "else-not-%s@.*@endif-%s"
1979       : "if-%s-then@.*@else-not-%s"),
1980       name, name);
1981
1982    err = map(exports, buf, 1, "", 1);
1983    if (err)
1984    {
1985       return err;
1986    }
1987
1988    snprintf(buf, 1000, (choose_first ? "if-%s-then" : "endif-%s"), name);
1989    return map(exports, buf, 1, "", 1);
1990 }
1991
1992
1993 /*********************************************************************
1994  *
1995  * Function    :  make_menu
1996  *
1997  * Description :  Returns an HTML-formatted menu of the available 
1998  *                unhidden CGIs, excluding the one given in <self>
1999  *
2000  * Parameters  :  self = name of CGI to leave out, can be NULL for
2001  *                complete listing.
2002  *
2003  * Returns     :  menu string, or NULL on out-of-memory error.
2004  *
2005  *********************************************************************/
2006 char *make_menu(const char *self)
2007 {
2008    const struct cgi_dispatcher *d;
2009    char *result = strdup("");
2010
2011    if (self == NULL)
2012    {
2013       self = "NO-SUCH-CGI!";
2014    }
2015
2016    /* List available unhidden CGI's and export as "other-cgis" */
2017    for (d = cgi_dispatchers; d->name; d++)
2018    {
2019       if (d->description && strcmp(d->name, self))
2020       {
2021          string_append(&result, "<li><a href=\"" CGI_PREFIX);
2022          string_append(&result, d->name);
2023          string_append(&result, "\">");
2024          string_append(&result, d->description);
2025          string_append(&result, "</a></li>");
2026       }
2027    }
2028
2029    return result;
2030 }
2031
2032
2033 /*********************************************************************
2034  *
2035  * Function    :  dump_map
2036  *
2037  * Description :  HTML-dump a map for debugging (as table)
2038  *
2039  * Parameters  :
2040  *          1  :  the_map = map to dump
2041  *
2042  * Returns     :  string with HTML
2043  *
2044  *********************************************************************/
2045 char *dump_map(const struct map *the_map)
2046 {
2047    struct map_entry *cur_entry;
2048    char *ret = strdup("");
2049
2050    string_append(&ret, "<table>\n");
2051
2052    for (cur_entry = the_map->first;
2053         (cur_entry != NULL) && (ret != NULL);
2054         cur_entry = cur_entry->next)
2055    {
2056       string_append(&ret, "<tr><td><b>");
2057       string_join  (&ret, html_encode(cur_entry->name));
2058       string_append(&ret, "</b></td><td>");
2059       string_join  (&ret, html_encode(cur_entry->value));
2060       string_append(&ret, "</td></tr>\n");
2061    }
2062
2063    string_append(&ret, "</table>\n");
2064    return ret;
2065 }
2066
2067
2068 /*
2069   Local Variables:
2070   tab-width: 3
2071   end:
2072 */