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