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