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