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