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