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