- Factor cgi_show_file() out of cgi_show_status().
[privoxy.git] / cgisimple.c
1 const char cgisimple_rcs[] = "$Id: cgisimple.c,v 1.70 2008/04/24 16:12:38 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/cgisimple.c,v $
5  *
6  * Purpose     :  Simple CGIs to get information about Privoxy's
7  *                status.
8  *                
9  *                Functions declared include:
10  * 
11  *
12  * Copyright   :  Written by and Copyright (C) 2001-2008 the SourceForge
13  *                Privoxy team. http://www.privoxy.org/
14  *
15  *                Based on the Internet Junkbuster originally written
16  *                by and Copyright (C) 1997 Anonymous Coders and 
17  *                Junkbusters Corporation.  http://www.junkbusters.com
18  *
19  *                This program is free software; you can redistribute it 
20  *                and/or modify it under the terms of the GNU General
21  *                Public License as published by the Free Software
22  *                Foundation; either version 2 of the License, or (at
23  *                your option) any later version.
24  *
25  *                This program is distributed in the hope that it will
26  *                be useful, but WITHOUT ANY WARRANTY; without even the
27  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
28  *                PARTICULAR PURPOSE.  See the GNU General Public
29  *                License for more details.
30  *
31  *                The GNU General Public License should be included with
32  *                this file.  If not, you can view it at
33  *                http://www.gnu.org/copyleft/gpl.html
34  *                or write to the Free Software Foundation, Inc., 59
35  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
36  *
37  * Revisions   :
38  *    $Log: cgisimple.c,v $
39  *    Revision 1.70  2008/04/24 16:12:38  fabiankeil
40  *    In cgi_show_status(), load the requested file at once.
41  *    Using string_join() for every line really doesn't scale.
42  *
43  *    Revision 1.69  2008/04/17 14:40:48  fabiankeil
44  *    Provide get_http_time() with the buffer size so it doesn't
45  *    have to blindly assume that the buffer is big enough.
46  *
47  *    Revision 1.68  2008/03/27 18:27:21  fabiankeil
48  *    Remove kill-popups action.
49  *
50  *    Revision 1.67  2008/03/27 17:00:05  fabiankeil
51  *    Turn the favicon blobs into locals.
52  *
53  *    Revision 1.66  2008/02/23 16:57:12  fabiankeil
54  *    Rename url_actions() to get_url_actions() and let it
55  *    use the standard parameter ordering.
56  *
57  *    Revision 1.65  2008/02/23 16:33:43  fabiankeil
58  *    Let forward_url() use the standard parameter ordering
59  *    and mark its second parameter immutable.
60  *
61  *    Revision 1.64  2008/02/03 13:56:07  fabiankeil
62  *    Add SOCKS5 support for show-url-info CGI page.
63  *
64  *    Revision 1.63  2008/02/01 06:04:31  fabiankeil
65  *    If edit buttons on the show-url-info CGI page are hidden, explain why.
66  *
67  *    Revision 1.62  2008/02/01 05:52:40  fabiankeil
68  *    Hide edit buttons on the show-url-info CGI page if enable-edit-action
69  *    is disabled. Patch by Lee with additional white space adjustments.
70  *
71  *    Revision 1.61  2008/01/26 11:13:25  fabiankeil
72  *    If enable-edit-actions is disabled, hide the edit buttons and explain why.
73  *
74  *    Revision 1.60  2007/10/27 13:12:13  fabiankeil
75  *    Finish 1.49 and check write access before
76  *    showing edit buttons on show-url-info page.
77  *
78  *    Revision 1.59  2007/10/19 16:42:36  fabiankeil
79  *    Plug memory leak I introduced five months ago.
80  *    Yay Valgrind and Privoxy-Regression-Test.
81  *
82  *    Revision 1.58  2007/07/21 12:19:50  fabiankeil
83  *    If show-url-info is called with an URL that Privoxy
84  *    would reject as invalid, don't show unresolved forwarding
85  *    variables, "final matches" or claim the site's secure.
86  *
87  *    Revision 1.57  2007/06/01 16:53:05  fabiankeil
88  *    Adjust cgi_show_url_info() to show what forward-override{}
89  *    would do with the requested URL (instead of showing how the
90  *    request for the CGI page would be forwarded if it wasn't a
91  *    CGI request).
92  *
93  *    Revision 1.56  2007/05/21 10:50:35  fabiankeil
94  *    - Use strlcpy() instead of strcpy().
95  *    - Stop treating actions files special. Expect a complete file name
96  *      (with or without path) like it's done for the rest of the files.
97  *      Closes FR#588084.
98  *    - Don't rerun sed() in cgi_show_request().
99  *
100  *    Revision 1.55  2007/04/13 13:36:46  fabiankeil
101  *    Reference action files in CGI URLs by id instead
102  *    of using the first part of the file name.
103  *    Fixes BR 1694250 and BR 1590556.
104  *
105  *    Revision 1.54  2007/04/09 18:11:35  fabiankeil
106  *    Don't mistake VC++'s _snprintf() for a snprintf() replacement.
107  *
108  *    Revision 1.53  2007/04/08 13:21:04  fabiankeil
109  *    Reference action files in CGI URLs by id instead
110  *    of using the first part of the file name.
111  *    Fixes BR 1694250 and BR 1590556.
112  *
113  *    Revision 1.52  2007/02/13 15:10:26  fabiankeil
114  *    Apparently fopen()ing in "binary" mode doesn't require
115  *    #ifdefs, it's already done without them in cgiedit.c.
116  *
117  *    Revision 1.51  2007/02/10 16:55:22  fabiankeil
118  *    - Show forwarding settings on the show-url-info page
119  *    - Fix some HTML syntax errors.
120  *
121  *    Revision 1.50  2007/01/23 15:51:17  fabiankeil
122  *    Add favicon delivery functions.
123  *
124  *    Revision 1.49  2007/01/20 16:29:38  fabiankeil
125  *    Suppress edit buttons for action files if Privoxy has
126  *    no write access. Suggested by Roland in PR 1564026.
127  *
128  *    Revision 1.48  2007/01/20 15:31:31  fabiankeil
129  *    Display warning if show-url-info CGI page
130  *    is used while Privoxy is toggled off.
131  *
132  *    Revision 1.47  2007/01/12 15:07:10  fabiankeil
133  *    Use zalloc in cgi_send_user_manual.
134  *
135  *    Revision 1.46  2007/01/02 12:49:46  fabiankeil
136  *    Add FEATURE_ZLIB to the list of conditional
137  *    defines at the show-status page.
138  *
139  *    Revision 1.45  2006/12/28 18:16:41  fabiankeil
140  *    Fixed gcc43 compiler warnings, zero out cgi_send_user_manual's
141  *    body memory before using it, replaced sprintf calls with snprintf.
142  *
143  *    Revision 1.44  2006/12/22 14:19:27  fabiankeil
144  *    Removed checks whether or not AF_FILES have
145  *    data structures associated with them in cgi_show_status.
146  *    It doesn't matter as we're only interested in the file names.
147  *
148  *    For the action files the checks were always true,
149  *    but they prevented empty filter files from being
150  *    listed. Fixes parts of BR 1619208.
151  *
152  *    Revision 1.43  2006/12/17 17:57:56  fabiankeil
153  *    - Added FEATURE_GRACEFUL_TERMINATION to the
154  *      "conditional #defines" section
155  *    - Escaped ampersands in generated HTML.
156  *    - Renamed re-filter-filename to re-filter-filenames
157  *
158  *    Revision 1.42  2006/11/21 15:43:12  fabiankeil
159  *    Add special treatment for WIN32 to make sure
160  *    cgi_send_user_manual opens the files in binary mode.
161  *    Fixes BR 1600411 and unbreaks image delivery.
162  *
163  *    Remove outdated comment.
164  *
165  *    Revision 1.41  2006/10/09 19:18:28  roro
166  *    Redirect http://p.p/user-manual (without trailing slash) to
167  *    http://p.p/user-manual/ (with trailing slash), otherwise links will be broken.
168  *
169  *    Revision 1.40  2006/09/09 13:05:33  fabiankeil
170  *    Modified cgi_send_user_manual to serve binary
171  *    content without destroying it first. Should also be
172  *    faster now. Added ".jpg" check for Content-Type guessing.
173  *
174  *    Revision 1.39  2006/09/08 09:49:23  fabiankeil
175  *    Deliver documents in the user-manual directory
176  *    with "Content-Type text/css" if their filename
177  *    ends with ".css".
178  *
179  *    Revision 1.38  2006/09/06 18:45:03  fabiankeil
180  *    Incorporate modified version of Roland Rosenfeld's patch to
181  *    optionally access the user-manual via Privoxy. Closes patch 679075.
182  *
183  *    Formatting changed to Privoxy style, added call to
184  *    cgi_error_no_template if the requested file doesn't
185  *    exist and modified check whether or not Privoxy itself
186  *    should serve the manual. Should work cross-platform now.
187  *
188  *    Revision 1.37  2006/07/18 14:48:45  david__schmidt
189  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
190  *    with what was really the latest development (the v_3_0_branch branch)
191  *
192  *    Revision 1.35.2.7  2006/01/29 23:10:56  david__schmidt
193  *    Multiple filter file support
194  *
195  *    Revision 1.35.2.6  2005/07/04 03:13:43  david__schmidt
196  *    Undo some damaging memory leak patches
197  *
198  *    Revision 1.35.2.5  2005/05/07 21:50:55  david__schmidt
199  *    A few memory leaks plugged (mostly on error paths)
200  *
201  *    Revision 1.35.2.4  2005/04/04 02:21:24  david__schmidt
202  *    Another instance of:
203  *    Don't show "Edit" buttons #ifndef FEATURE_CGI_EDIT_ACTIONS
204  *    Thanks to Magnus Holmgren for the patch
205  *
206  *    Revision 1.35.2.3  2003/12/17 16:34:15  oes
207  *     - Prevent line wrap beween "View/Edit" link buttons on status page
208  *     - Some (mostly irrelevant) fixes for Out-of-mem-case handling
209  *
210  *    Revision 1.35.2.2  2003/04/03 13:48:28  oes
211  *    Don't show "Edit" buttons #ifndef FEATURE_CGI_EDIT_ACTIONS
212  *
213  *    Revision 1.35.2.1  2002/07/04 15:02:38  oes
214  *    Added ability to send redirects to send-banner CGI, so that it can completely mimic the image blocking action if called with type=auto
215  *
216  *    Revision 1.35.2.1  2002/07/01 17:32:04  morcego
217  *    Applying patch from Andreas as provided by Hal on the list.
218  *    Message-ID: <20020701121218.V1606@feenix.burgiss.net>
219  *
220  *    Revision 1.35  2002/05/12 21:44:44  jongfoster
221  *    Adding amiga.[ch] revision information, if on an amiga.
222  *
223  *    Revision 1.34  2002/04/30 12:06:12  oes
224  *    Deleted unused code from default_cgi
225  *
226  *    Revision 1.33  2002/04/30 11:14:52  oes
227  *    Made csp the first parameter in *action_to_html
228  *
229  *    Revision 1.32  2002/04/26 18:29:13  jongfoster
230  *    Fixing this Visual C++ warning:
231  *    cgisimple.c(775) : warning C4018: '<' : signed/unsigned mismatch
232  *
233  *    Revision 1.31  2002/04/26 12:54:36  oes
234  *     - Kill obsolete REDIRECT_URL code
235  *     - Error handling fixes
236  *     - Style sheet related HTML snipplet changes
237  *     - cgi_show_url_info:
238  *       - Matches now in table, actions on single lines,
239  *         linked to help
240  *       - standard.action suppressed
241  *       - Buttons to View and Edit AFs
242  *
243  *    Revision 1.30  2002/04/24 02:18:08  oes
244  *     - show-status is now the starting point for editing
245  *       the actions files, generate list of all AFs with buttons
246  *       for viewing and editing, new look for file list (Jon:
247  *       buttons now aligned ;-P ), view mode now supports multiple
248  *       AFs, name changes, no view links for unspecified files,
249  *       no edit link for standard.action.
250  *
251  *     - Jon's multiple AF patch: cgi_show_url_info now uses all
252  *       AFs and marks the output accordingly
253  *
254  *    Revision 1.29  2002/04/10 13:38:35  oes
255  *    load_template signature changed
256  *
257  *    Revision 1.28  2002/04/07 15:42:12  jongfoster
258  *    Fixing send-banner?type=auto when the image-blocker is
259  *    a redirect to send-banner
260  *
261  *    Revision 1.27  2002/04/05 15:50:48  oes
262  *    added send-stylesheet CGI
263  *
264  *    Revision 1.26  2002/04/04 00:36:36  gliptak
265  *    always use pcre for matching
266  *
267  *    Revision 1.25  2002/04/03 22:28:03  gliptak
268  *    Removed references to gnu_regex
269  *
270  *    Revision 1.24  2002/04/02 16:12:47  oes
271  *    Fix: moving misplaced lines into #ifdef FEATURE_FORCE
272  *
273  *    Revision 1.23  2002/03/26 22:29:54  swa
274  *    we have a new homepage!
275  *
276  *    Revision 1.22  2002/03/24 16:18:15  jongfoster
277  *    Removing old logo
278  *
279  *    Revision 1.21  2002/03/24 15:23:33  jongfoster
280  *    Name changes
281  *
282  *    Revision 1.20  2002/03/24 13:25:43  swa
283  *    name change related issues
284  *
285  *    Revision 1.19  2002/03/16 23:54:06  jongfoster
286  *    Adding graceful termination feature, to help look for memory leaks.
287  *    If you enable this (which, by design, has to be done by hand
288  *    editing config.h) and then go to http://i.j.b/die, then the program
289  *    will exit cleanly after the *next* request.  It should free all the
290  *    memory that was used.
291  *
292  *    Revision 1.18  2002/03/12 01:44:49  oes
293  *    Changed default for "blocked" image from jb logo to checkboard pattern
294  *
295  *    Revision 1.17  2002/03/08 16:43:18  oes
296  *    Added choice beween GIF and PNG built-in images
297  *
298  *    Revision 1.16  2002/03/07 03:48:38  oes
299  *     - Changed built-in images from GIF to PNG
300  *       (with regard to Unisys patent issue)
301  *     - Added a 4x4 pattern PNG which is less intrusive
302  *       than the logo but also clearly marks the deleted banners
303  *
304  *    Revision 1.15  2002/03/06 22:54:35  jongfoster
305  *    Automated function-comment nitpicking.
306  *
307  *    Revision 1.14  2002/03/02 04:14:50  david__schmidt
308  *    Clean up a little CRLF unpleasantness that suddenly appeared
309  *
310  *    Revision 1.13  2002/02/21 00:10:37  jongfoster
311  *    Adding send-banner?type=auto option
312  *
313  *    Revision 1.12  2002/01/23 01:03:32  jongfoster
314  *    Fixing gcc [CygWin] compiler warnings
315  *
316  *    Revision 1.11  2002/01/23 00:01:04  jongfoster
317  *    Adding cgi_transparent_gif() for http://i.j.b/t
318  *    Adding missing html_encode() to many CGI functions.
319  *    Adding urlmatch.[ch] to http://i.j.b/show-version
320  *
321  *    Revision 1.10  2002/01/17 21:10:37  jongfoster
322  *    Changes to cgi_show_url_info to use new matching code from urlmatch.c.
323  *    Also fixing a problem in the same function with improperly quoted URLs
324  *    in output HTML, and adding code to handle https:// URLs correctly.
325  *
326  *    Revision 1.9  2001/11/30 23:09:15  jongfoster
327  *    Now reports on FEATURE_CGI_EDIT_ACTIONS
328  *    Removing FEATURE_DENY_GZIP from template
329  *
330  *    Revision 1.8  2001/11/13 00:14:07  jongfoster
331  *    Fixing stupid bug now I've figured out what || means.
332  *    (It always returns 0 or 1, not one of it's paramaters.)
333  *
334  *    Revision 1.7  2001/10/23 21:48:19  jongfoster
335  *    Cleaning up error handling in CGI functions - they now send back
336  *    a HTML error page and should never cause a FATAL error.  (Fixes one
337  *    potential source of "denial of service" attacks).
338  *
339  *    CGI actions file editor that works and is actually useful.
340  *
341  *    Ability to toggle JunkBuster remotely using a CGI call.
342  *
343  *    You can turn off both the above features in the main configuration
344  *    file, e.g. if you are running a multi-user proxy.
345  *
346  *    Revision 1.6  2001/10/14 22:00:32  jongfoster
347  *    Adding support for a 404 error when an invalid CGI page is requested.
348  *
349  *    Revision 1.5  2001/10/07 15:30:41  oes
350  *    Removed FEATURE_DENY_GZIP
351  *
352  *    Revision 1.4  2001/10/02 15:31:12  oes
353  *    Introduced show-request cgi
354  *
355  *    Revision 1.3  2001/09/22 16:34:44  jongfoster
356  *    Removing unneeded #includes
357  *
358  *    Revision 1.2  2001/09/19 18:01:11  oes
359  *    Fixed comments; cosmetics
360  *
361  *    Revision 1.1  2001/09/16 17:08:54  jongfoster
362  *    Moving simple CGI functions from cgi.c to new file cgisimple.c
363  *
364  *
365  **********************************************************************/
366 \f
367
368 #include "config.h"
369
370 #include <stdio.h>
371 #include <sys/types.h>
372 #include <stdlib.h>
373 #include <ctype.h>
374 #include <string.h>
375 #include <assert.h>
376
377 #ifdef HAVE_ACCESS
378 #include <unistd.h>
379 #endif /* def HAVE_ACCESS */
380
381 #include "project.h"
382 #include "cgi.h"
383 #include "cgisimple.h"
384 #include "list.h"
385 #include "encode.h"
386 #include "jcc.h"
387 #include "filters.h"
388 #include "actions.h"
389 #include "miscutil.h"
390 #include "loadcfg.h"
391 #include "parsers.h"
392 #include "urlmatch.h"
393 #include "errlog.h"
394
395 const char cgisimple_h_rcs[] = CGISIMPLE_H_VERSION;
396
397 static char *show_rcs(void);
398 static jb_err show_defines(struct map *exports);
399 static jb_err cgi_show_file(struct client_state *csp,
400                             struct http_response *rsp,
401                             const struct map *parameters);
402
403 /*********************************************************************
404  *
405  * Function    :  cgi_default
406  *
407  * Description :  CGI function that is called for the CGI_SITE_1_HOST
408  *                and CGI_SITE_2_HOST/CGI_SITE_2_PATH base URLs.
409  *                Boring - only exports the default exports.
410  *               
411  * Parameters  :
412  *          1  :  csp = Current client state (buffers, headers, etc...)
413  *          2  :  rsp = http_response data structure for output
414  *          3  :  parameters = map of cgi parameters
415  *
416  * CGI Parameters : none
417  *
418  * Returns     :  JB_ERR_OK on success
419  *                JB_ERR_MEMORY on out-of-memory
420  *
421  *********************************************************************/
422 jb_err cgi_default(struct client_state *csp,
423                    struct http_response *rsp,
424                    const struct map *parameters)
425 {
426    struct map *exports;
427
428    assert(csp);
429    assert(rsp);
430
431    if (NULL == (exports = default_exports(csp, "")))
432    {
433       return JB_ERR_MEMORY;
434    }
435
436    return template_fill_for_cgi(csp, "default", exports, rsp);
437 }
438
439
440 /*********************************************************************
441  *
442  * Function    :  cgi_error_404
443  *
444  * Description :  CGI function that is called if an unknown action was
445  *                given.
446  *               
447  * Parameters  :
448  *          1  :  csp = Current client state (buffers, headers, etc...)
449  *          2  :  rsp = http_response data structure for output
450  *          3  :  parameters = map of cgi parameters
451  *
452  * CGI Parameters : none
453  *
454  * Returns     :  JB_ERR_OK on success
455  *                JB_ERR_MEMORY on out-of-memory error.  
456  *
457  *********************************************************************/
458 jb_err cgi_error_404(struct client_state *csp,
459                      struct http_response *rsp,
460                      const struct map *parameters)
461 {
462    struct map *exports;
463
464    assert(csp);
465    assert(rsp);
466    assert(parameters);
467
468    if (NULL == (exports = default_exports(csp, NULL)))
469    {
470       return JB_ERR_MEMORY;
471    }
472
473    rsp->status = strdup("404 Privoxy configuration page not found");
474    if (rsp->status == NULL)
475    {
476       free_map(exports);
477       return JB_ERR_MEMORY;
478    }
479
480    return template_fill_for_cgi(csp, "cgi-error-404", exports, rsp);
481 }
482
483
484 #ifdef FEATURE_GRACEFUL_TERMINATION
485 /*********************************************************************
486  *
487  * Function    :  cgi_die
488  *
489  * Description :  CGI function to shut down Privoxy.
490  *                NOTE: Turning this on in a production build
491  *                would be a BAD idea.  An EXTREMELY BAD idea.
492  *                In short, don't do it.
493  *               
494  * Parameters  :
495  *          1  :  csp = Current client state (buffers, headers, etc...)
496  *          2  :  rsp = http_response data structure for output
497  *          3  :  parameters = map of cgi parameters
498  *
499  * CGI Parameters : none
500  *
501  * Returns     :  JB_ERR_OK on success
502  *                JB_ERR_MEMORY on out-of-memory error.  
503  *
504  *********************************************************************/
505 jb_err cgi_die (struct client_state *csp,
506                 struct http_response *rsp,
507                 const struct map *parameters)
508 {
509    assert(csp);
510    assert(rsp);
511    assert(parameters);
512
513    /* quit */
514    g_terminate = 1;
515
516    /*
517     * I don't really care what gets sent back to the browser.
518     * Take the easy option - "out of memory" page.
519     */
520
521    return JB_ERR_MEMORY;
522 }
523 #endif /* def FEATURE_GRACEFUL_TERMINATION */
524
525
526 /*********************************************************************
527  *
528  * Function    :  cgi_show_request
529  *
530  * Description :  Show the client's request and what sed() would have
531  *                made of it.
532  *               
533  * Parameters  :
534  *          1  :  csp = Current client state (buffers, headers, etc...)
535  *          2  :  rsp = http_response data structure for output
536  *          3  :  parameters = map of cgi parameters
537  *
538  * CGI Parameters : none
539  *
540  * Returns     :  JB_ERR_OK on success
541  *                JB_ERR_MEMORY on out-of-memory error.  
542  *
543  *********************************************************************/
544 jb_err cgi_show_request(struct client_state *csp,
545                         struct http_response *rsp,
546                         const struct map *parameters)
547 {
548    char *p;
549    struct map *exports;
550
551    assert(csp);
552    assert(rsp);
553    assert(parameters);
554
555    if (NULL == (exports = default_exports(csp, "show-request")))
556    {
557       return JB_ERR_MEMORY;
558    }
559    
560    /*
561     * Repair the damage done to the IOB by get_header()
562     */
563    for (p = csp->iob->buf; p < csp->iob->eod; p++)
564    {
565       if (*p == '\0') *p = '\n';
566    }
567
568    /*
569     * Export the original client's request and the one we would
570     * be sending to the server if this wasn't a CGI call
571     */
572
573    if (map(exports, "client-request", 1, html_encode(csp->iob->buf), 0))
574    {
575       free_map(exports);
576       return JB_ERR_MEMORY;
577    }
578
579    if (map(exports, "processed-request", 1,
580          html_encode_and_free_original(list_to_text(csp->headers)), 0))
581    {
582       free_map(exports);
583       return JB_ERR_MEMORY;
584    }
585
586    return template_fill_for_cgi(csp, "show-request", exports, rsp);
587 }
588
589
590 /*********************************************************************
591  *
592  * Function    :  cgi_send_banner
593  *
594  * Description :  CGI function that returns a banner. 
595  *
596  * Parameters  :
597  *          1  :  csp = Current client state (buffers, headers, etc...)
598  *          2  :  rsp = http_response data structure for output
599  *          3  :  parameters = map of cgi parameters
600  *
601  * CGI Parameters :
602  *           type : Selects the type of banner between "trans", "logo",
603  *                  and "auto". Defaults to "logo" if absent or invalid.
604  *                  "auto" means to select as if we were image-blocking.
605  *                  (Only the first character really counts; b and t are
606  *                  equivalent).
607  *
608  * Returns     :  JB_ERR_OK on success
609  *                JB_ERR_MEMORY on out-of-memory error.  
610  *
611  *********************************************************************/
612 jb_err cgi_send_banner(struct client_state *csp,
613                        struct http_response *rsp,
614                        const struct map *parameters)
615 {
616    char imagetype = lookup(parameters, "type")[0];
617
618    /*
619     * If type is auto, then determine the right thing
620     * to do from the set-image-blocker action
621     */
622    if (imagetype == 'a') 
623    {
624       /*
625        * Default to pattern
626        */
627       imagetype = 'p';
628
629 #ifdef FEATURE_IMAGE_BLOCKING
630       if ((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
631       {
632          static const char prefix1[] = CGI_PREFIX "send-banner?type=";
633          static const char prefix2[] = "http://" CGI_SITE_1_HOST "/send-banner?type=";
634          const char *p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
635
636          if (p == NULL)
637          {
638             /* Use default - nothing to do here. */
639          }
640          else if (0 == strcmpic(p, "blank"))
641          {
642             imagetype = 'b';
643          }
644          else if (0 == strcmpic(p, "pattern"))
645          {
646             imagetype = 'p';
647          }
648
649          /*
650           * If the action is to call this CGI, determine
651           * the argument:
652           */
653          else if (0 == strncmpic(p, prefix1, sizeof(prefix1) - 1))
654          {
655             imagetype = p[sizeof(prefix1) - 1];
656          }
657          else if (0 == strncmpic(p, prefix2, sizeof(prefix2) - 1))
658          {
659             imagetype = p[sizeof(prefix2) - 1];
660          }
661
662          /*
663           * Everything else must (should) be a URL to
664           * redirect to.
665           */
666          else
667          {
668             imagetype = 'r';
669          }
670       }
671 #endif /* def FEATURE_IMAGE_BLOCKING */
672    }
673       
674    /*
675     * Now imagetype is either the non-auto type we were called with,
676     * or it was auto and has since been determined. In any case, we
677     * can proceed to actually answering the request by sending a redirect
678     * or an image as appropriate:
679     */
680    if (imagetype == 'r') 
681    {
682       rsp->status = strdup("302 Local Redirect from Privoxy");
683       if (rsp->status == NULL)
684       {
685          return JB_ERR_MEMORY;
686       }
687       if (enlist_unique_header(rsp->headers, "Location",
688                                csp->action->string[ACTION_STRING_IMAGE_BLOCKER]))
689       {
690          return JB_ERR_MEMORY;
691       }
692    }
693    else
694    {
695       if ((imagetype == 'b') || (imagetype == 't')) 
696       {
697          rsp->body = bindup(image_blank_data, image_blank_length);
698          rsp->content_length = image_blank_length;
699       }
700       else
701       {
702          rsp->body = bindup(image_pattern_data, image_pattern_length);
703          rsp->content_length = image_pattern_length;
704       }
705
706       if (rsp->body == NULL)
707       {
708          return JB_ERR_MEMORY;
709       }
710       if (enlist(rsp->headers, "Content-Type: " BUILTIN_IMAGE_MIMETYPE))
711       {
712          return JB_ERR_MEMORY;
713       }
714
715       rsp->is_static = 1;
716    }
717
718    return JB_ERR_OK;
719
720 }
721
722
723 /*********************************************************************
724  *
725  * Function    :  cgi_transparent_image
726  *
727  * Description :  CGI function that sends a 1x1 transparent image.
728  *
729  * Parameters  :
730  *          1  :  csp = Current client state (buffers, headers, etc...)
731  *          2  :  rsp = http_response data structure for output
732  *          3  :  parameters = map of cgi parameters
733  *
734  * CGI Parameters : None
735  *
736  * Returns     :  JB_ERR_OK on success
737  *                JB_ERR_MEMORY on out-of-memory error.  
738  *
739  *********************************************************************/
740 jb_err cgi_transparent_image(struct client_state *csp,
741                              struct http_response *rsp,
742                              const struct map *parameters)
743 {
744    rsp->body = bindup(image_blank_data, image_blank_length);
745    rsp->content_length = image_blank_length;
746
747    if (rsp->body == NULL)
748    {
749       return JB_ERR_MEMORY;
750    }
751
752    if (enlist(rsp->headers, "Content-Type: " BUILTIN_IMAGE_MIMETYPE))
753    {
754       return JB_ERR_MEMORY;
755    }
756
757    rsp->is_static = 1;
758
759    return JB_ERR_OK;
760
761 }
762
763
764 /*********************************************************************
765  *
766  * Function    :  cgi_send_default_favicon
767  *
768  * Description :  CGI function that sends the standard favicon.
769  *
770  * Parameters  :
771  *          1  :  csp = Current client state (buffers, headers, etc...)
772  *          2  :  rsp = http_response data structure for output
773  *          3  :  parameters = map of cgi parameters
774  *
775  * CGI Parameters : None
776  *
777  * Returns     :  JB_ERR_OK on success
778  *                JB_ERR_MEMORY on out-of-memory error.  
779  *
780  *********************************************************************/
781 jb_err cgi_send_default_favicon(struct client_state *csp,
782                                 struct http_response *rsp,
783                                 const struct map *parameters)
784 {
785    static const char default_favicon_data[] =
786       "\000\000\001\000\001\000\020\020\002\000\000\000\000\000\260"
787       "\000\000\000\026\000\000\000\050\000\000\000\020\000\000\000"
788       "\040\000\000\000\001\000\001\000\000\000\000\000\100\000\000"
789       "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000"
790       "\000\000\377\377\377\000\377\000\052\000\017\360\000\000\077"
791       "\374\000\000\161\376\000\000\161\376\000\000\361\377\000\000"
792       "\361\377\000\000\360\017\000\000\360\007\000\000\361\307\000"
793       "\000\361\307\000\000\361\307\000\000\360\007\000\000\160\036"
794       "\000\000\177\376\000\000\077\374\000\000\017\360\000\000\360"
795       "\017\000\000\300\003\000\000\200\001\000\000\200\001\000\000"
796       "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
797       "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
798       "\000\000\200\001\000\000\200\001\000\000\300\003\000\000\360"
799       "\017\000\000";
800    static const size_t favicon_length = sizeof(default_favicon_data) - 1;
801
802    rsp->body = bindup(default_favicon_data, favicon_length);
803    rsp->content_length = favicon_length;
804
805    if (rsp->body == NULL)
806    {
807       return JB_ERR_MEMORY;
808    }
809
810    if (enlist(rsp->headers, "Content-Type: image/x-icon"))
811    {
812       return JB_ERR_MEMORY;
813    }
814
815    rsp->is_static = 1;
816
817    return JB_ERR_OK;
818
819 }
820
821
822 /*********************************************************************
823  *
824  * Function    :  cgi_send_error_favicon
825  *
826  * Description :  CGI function that sends the favicon for error pages.
827  *
828  * Parameters  :
829  *          1  :  csp = Current client state (buffers, headers, etc...)
830  *          2  :  rsp = http_response data structure for output
831  *          3  :  parameters = map of cgi parameters
832  *
833  * CGI Parameters : None
834  *
835  * Returns     :  JB_ERR_OK on success
836  *                JB_ERR_MEMORY on out-of-memory error.  
837  *
838  *********************************************************************/
839 jb_err cgi_send_error_favicon(struct client_state *csp,
840                               struct http_response *rsp,
841                               const struct map *parameters)
842 {
843    static const char error_favicon_data[] =
844       "\000\000\001\000\001\000\020\020\002\000\000\000\000\000\260"
845       "\000\000\000\026\000\000\000\050\000\000\000\020\000\000\000"
846       "\040\000\000\000\001\000\001\000\000\000\000\000\100\000\000"
847       "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000"
848       "\000\000\377\377\377\000\000\000\377\000\017\360\000\000\077"
849       "\374\000\000\161\376\000\000\161\376\000\000\361\377\000\000"
850       "\361\377\000\000\360\017\000\000\360\007\000\000\361\307\000"
851       "\000\361\307\000\000\361\307\000\000\360\007\000\000\160\036"
852       "\000\000\177\376\000\000\077\374\000\000\017\360\000\000\360"
853       "\017\000\000\300\003\000\000\200\001\000\000\200\001\000\000"
854       "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
855       "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
856       "\000\000\200\001\000\000\200\001\000\000\300\003\000\000\360"
857       "\017\000\000";
858    static const size_t favicon_length = sizeof(error_favicon_data) - 1;
859
860    rsp->body = bindup(error_favicon_data, favicon_length);
861    rsp->content_length = favicon_length;
862
863    if (rsp->body == NULL)
864    {
865       return JB_ERR_MEMORY;
866    }
867
868    if (enlist(rsp->headers, "Content-Type: image/x-icon"))
869    {
870       return JB_ERR_MEMORY;
871    }
872
873    rsp->is_static = 1;
874
875    return JB_ERR_OK;
876
877 }
878
879
880 /*********************************************************************
881  *
882  * Function    :  cgi_send_stylesheet
883  *
884  * Description :  CGI function that sends a css stylesheet found
885  *                in the cgi-style.css template
886  *
887  * Parameters  :
888  *          1  :  csp = Current client state (buffers, headers, etc...)
889  *          2  :  rsp = http_response data structure for output
890  *          3  :  parameters = map of cgi parameters
891  *
892  * CGI Parameters : None
893  *
894  * Returns     :  JB_ERR_OK on success
895  *                JB_ERR_MEMORY on out-of-memory error.  
896  *
897  *********************************************************************/
898 jb_err cgi_send_stylesheet(struct client_state *csp,
899                            struct http_response *rsp,
900                            const struct map *parameters)
901 {
902    jb_err err;
903    
904    assert(csp);
905    assert(rsp);
906
907    err = template_load(csp, &rsp->body, "cgi-style.css", 0);
908
909    if (err == JB_ERR_FILE)
910    {
911       /*
912        * No way to tell user; send empty stylesheet
913        */
914       log_error(LOG_LEVEL_ERROR, "Could not find cgi-style.css template");
915    }
916    else if (err)
917    {
918       return err; /* JB_ERR_MEMORY */
919    }
920
921    if (enlist(rsp->headers, "Content-Type: text/css"))
922    {
923       return JB_ERR_MEMORY;
924    }
925
926    return JB_ERR_OK;
927
928 }
929 /*********************************************************************
930  *
931  * Function    :  cgi_send_user_manual
932  *
933  * Description :  CGI function that sends a file in the user
934  *                manual directory.
935  *
936  * Parameters  :
937  *          1  :  csp = Current client state (buffers, headers, etc...)
938  *          2  :  rsp = http_response data structure for output
939  *          3  :  parameters = map of cgi parameters
940  *
941  * CGI Parameters : file=name.html, the name of the HTML file
942  *                  (relative to user-manual from config)
943  *
944  * Returns     :  JB_ERR_OK on success
945  *                JB_ERR_MEMORY on out-of-memory error.  
946  *
947  *********************************************************************/
948 jb_err cgi_send_user_manual(struct client_state *csp,
949                             struct http_response *rsp,
950                             const struct map *parameters)
951 {
952    const char * filename;
953    char *full_path;
954    FILE *fp;
955    jb_err err = JB_ERR_OK;
956    size_t length;
957
958    assert(csp);
959    assert(rsp);
960    assert(parameters);
961
962    if (!parameters->first)
963    {
964       /* requested http://p.p/user-manual (without trailing slash) */
965       return cgi_redirect(rsp, CGI_PREFIX "user-manual/");
966    }
967
968    get_string_param(parameters, "file", &filename);
969    /* Check paramter for hack attempts */
970    if (filename && strchr(filename, '/'))
971    {
972       return JB_ERR_CGI_PARAMS;
973    }
974    if (filename && strstr(filename, ".."))
975    {
976       return JB_ERR_CGI_PARAMS;
977    }
978
979    full_path = make_path(csp->config->usermanual, filename ? filename : "index.html");
980    if (full_path == NULL)
981    {
982       return JB_ERR_MEMORY;
983    }
984
985    /* Open user-manual file */
986    if (NULL == (fp = fopen(full_path, "rb")))
987    {
988       log_error(LOG_LEVEL_ERROR, "Cannot open user-manual file %s: %E", full_path);
989       err = cgi_error_no_template(csp, rsp, full_path);
990       free(full_path);
991       return err;
992    }
993
994    /* Get file length */
995    fseek(fp, 0, SEEK_END);
996    length = (size_t)ftell(fp);
997    fseek(fp, 0, SEEK_SET);
998
999    /* Allocate memory and load the file directly into the body */
1000    rsp->body = (char *)zalloc(length+1);
1001    if (!rsp->body)
1002    {
1003       fclose(fp);
1004       free(full_path);
1005       return JB_ERR_MEMORY;
1006    }
1007    if (!fread(rsp->body, length, 1, fp))
1008    {
1009       /*
1010        * May happen if the file size changes between fseek() and fread().
1011        * If it does, we just log it and serve what we got.
1012        */
1013       log_error(LOG_LEVEL_ERROR, "Couldn't completely read user-manual file %s.", full_path);
1014    }
1015    fclose(fp);
1016    free(full_path);
1017
1018    rsp->content_length = length;
1019
1020    /* Guess correct Content-Type based on the filename's ending */
1021    if (filename)
1022    {
1023       length = strlen(filename);
1024    }
1025    else
1026    {
1027       length = 0;
1028    } 
1029    if((length>=4) && !strcmp(&filename[length-4], ".css"))
1030    {
1031       err = enlist(rsp->headers, "Content-Type: text/css");
1032    }
1033    else if((length>=4) && !strcmp(&filename[length-4], ".jpg"))
1034    {
1035       err = enlist(rsp->headers, "Content-Type: image/jpeg");
1036    }
1037    else
1038    {
1039       err = enlist(rsp->headers, "Content-Type: text/html");
1040    }
1041
1042    return err;
1043 }
1044
1045
1046 /*********************************************************************
1047  *
1048  * Function    :  cgi_show_version
1049  *
1050  * Description :  CGI function that returns a a web page describing the
1051  *                file versions of Privoxy.
1052  *
1053  * Parameters  :
1054  *          1  :  csp = Current client state (buffers, headers, etc...)
1055  *          2  :  rsp = http_response data structure for output
1056  *          3  :  parameters = map of cgi parameters
1057  *
1058  * CGI Parameters : none
1059  *
1060  * Returns     :  JB_ERR_OK on success
1061  *                JB_ERR_MEMORY on out-of-memory error.  
1062  *
1063  *********************************************************************/
1064 jb_err cgi_show_version(struct client_state *csp,
1065                         struct http_response *rsp,
1066                         const struct map *parameters)
1067 {
1068    struct map *exports;
1069
1070    assert(csp);
1071    assert(rsp);
1072    assert(parameters);
1073
1074    if (NULL == (exports = default_exports(csp, "show-version")))
1075    {
1076       return JB_ERR_MEMORY;
1077    }
1078
1079    if (map(exports, "sourceversions", 1, show_rcs(), 0))
1080    {
1081       free_map(exports);
1082       return JB_ERR_MEMORY;
1083    }
1084
1085    return template_fill_for_cgi(csp, "show-version", exports, rsp);
1086 }
1087
1088
1089 /*********************************************************************
1090  *
1091  * Function    :  cgi_show_status
1092  *
1093  * Description :  CGI function that returns a web page describing the
1094  *                current status of Privoxy.
1095  *
1096  * Parameters  :
1097  *          1  :  csp = Current client state (buffers, headers, etc...)
1098  *          2  :  rsp = http_response data structure for output
1099  *          3  :  parameters = map of cgi parameters
1100  *
1101  * CGI Parameters :
1102  *        file :  Which file to show.  Only first letter is checked,
1103  *                valid values are:
1104  *                - "a"ction file
1105  *                - "r"egex
1106  *                - "t"rust
1107  *                Default is to show menu and other information.
1108  *
1109  * Returns     :  JB_ERR_OK on success
1110  *                JB_ERR_MEMORY on out-of-memory error.  
1111  *
1112  *********************************************************************/
1113 jb_err cgi_show_status(struct client_state *csp,
1114                        struct http_response *rsp,
1115                        const struct map *parameters)
1116 {
1117    char *s = NULL;
1118    unsigned i;
1119    int j;
1120
1121    char buf[BUFFER_SIZE];
1122 #ifdef FEATURE_STATISTICS
1123    float perc_rej;   /* Percentage of http requests rejected */
1124    int local_urls_read;
1125    int local_urls_rejected;
1126 #endif /* ndef FEATURE_STATISTICS */
1127    jb_err err = JB_ERR_OK;
1128
1129    struct map *exports;
1130
1131    assert(csp);
1132    assert(rsp);
1133    assert(parameters);
1134
1135    if ('\0' != *(lookup(parameters, "file")))
1136    {
1137       return cgi_show_file(csp, rsp, parameters);
1138    }
1139
1140    if (NULL == (exports = default_exports(csp, "show-status")))
1141    {
1142       return JB_ERR_MEMORY;
1143    }
1144
1145    s = strdup("");
1146    for (j = 0; (s != NULL) && (j < Argc); j++)
1147    {
1148       if (!err) err = string_join  (&s, html_encode(Argv[j]));
1149       if (!err) err = string_append(&s, " ");
1150    }
1151    if (!err) err = map(exports, "invocation", 1, s, 0);
1152
1153    if (!err) err = map(exports, "options", 1, csp->config->proxy_args, 1);
1154    if (!err) err = show_defines(exports);
1155
1156    if (err) 
1157    {
1158       free_map(exports);
1159       return JB_ERR_MEMORY;
1160    }
1161
1162 #ifdef FEATURE_STATISTICS
1163    local_urls_read     = urls_read;
1164    local_urls_rejected = urls_rejected;
1165
1166    /*
1167     * Need to alter the stats not to include the fetch of this
1168     * page.
1169     *
1170     * Can't do following thread safely! doh!
1171     *
1172     * urls_read--;
1173     * urls_rejected--; * This will be incremented subsequently *
1174     */
1175
1176    if (local_urls_read == 0)
1177    {
1178       if (!err) err = map_block_killer(exports, "have-stats");
1179    }
1180    else
1181    {
1182       if (!err) err = map_block_killer(exports, "have-no-stats");
1183
1184       perc_rej = (float)local_urls_rejected * 100.0F /
1185             (float)local_urls_read;
1186
1187       snprintf(buf, sizeof(buf), "%d", local_urls_read);
1188       if (!err) err = map(exports, "requests-received", 1, buf, 1);
1189
1190       snprintf(buf, sizeof(buf), "%d", local_urls_rejected);
1191       if (!err) err = map(exports, "requests-blocked", 1, buf, 1);
1192
1193       snprintf(buf, sizeof(buf), "%6.2f", perc_rej);
1194       if (!err) err = map(exports, "percent-blocked", 1, buf, 1);
1195    }
1196
1197 #else /* ndef FEATURE_STATISTICS */
1198    err = err || map_block_killer(exports, "statistics");
1199 #endif /* ndef FEATURE_STATISTICS */
1200    
1201    /* 
1202     * List all action files in use, together with view and edit links,
1203     * except for standard.action, which should only be viewable. (Not
1204     * enforced in the editor itself)
1205     * FIXME: Shouldn't include hardwired HTML here, use line template instead!
1206     */
1207    s = strdup("");
1208    for (i = 0; i < MAX_AF_FILES; i++)
1209    {
1210       if (csp->actions_list[i] != NULL)
1211       {
1212          if (!err) err = string_append(&s, "<tr><td>");
1213          if (!err) err = string_join(&s, html_encode(csp->actions_list[i]->filename));
1214          snprintf(buf, sizeof(buf),
1215             "</td><td class=\"buttons\"><a href=\"/show-status?file=actions&amp;index=%d\">View</a>", i);
1216          if (!err) err = string_append(&s, buf);
1217
1218 #ifdef FEATURE_CGI_EDIT_ACTIONS
1219          if ((csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS)
1220             && (NULL == strstr(csp->actions_list[i]->filename, "standard.action"))
1221             && (NULL != csp->config->actions_file_short[i]))
1222          {
1223 #ifdef HAVE_ACCESS
1224             if (access(csp->config->actions_file[i], W_OK) == 0)
1225             {
1226 #endif /* def HAVE_ACCESS */
1227                snprintf(buf, sizeof(buf), "&nbsp;&nbsp;<a href=\"/edit-actions-list?f=%d\">Edit</a>", i);
1228                if (!err) err = string_append(&s, buf);
1229 #ifdef HAVE_ACCESS
1230             }
1231             else
1232             {
1233                if (!err) err = string_append(&s, "&nbsp;&nbsp;<strong>No write access.</strong>");
1234             }
1235 #endif /* def HAVE_ACCESS */
1236          }
1237 #endif
1238
1239          if (!err) err = string_append(&s, "</td></tr>\n");
1240       }
1241    }
1242    if (*s != '\0')   
1243    {
1244       if (!err) err = map(exports, "actions-filenames", 1, s, 0);
1245    }
1246    else
1247    {
1248       if (!err) err = map(exports, "actions-filenames", 1, "<tr><td>None specified</td></tr>", 1);
1249    }
1250
1251    /* 
1252     * List all re_filterfiles in use, together with view options.
1253     * FIXME: Shouldn't include hardwired HTML here, use line template instead!
1254     */
1255    s = strdup("");
1256    for (i = 0; i < MAX_AF_FILES; i++)
1257    {
1258       if (csp->rlist[i] != NULL)
1259       {
1260          if (!err) err = string_append(&s, "<tr><td>");
1261          if (!err) err = string_join(&s, html_encode(csp->rlist[i]->filename));
1262          snprintf(buf, 100,
1263             "</td><td class=\"buttons\"><a href=\"/show-status?file=filter&amp;index=%d\">View</a>", i);
1264          if (!err) err = string_append(&s, buf);
1265          if (!err) err = string_append(&s, "</td></tr>\n");
1266       }
1267    }
1268    if (*s != '\0')   
1269    {
1270       if (!err) err = map(exports, "re-filter-filenames", 1, s, 0);
1271    }
1272    else
1273    {
1274       if (!err) err = map(exports, "re-filter-filenames", 1, "<tr><td>None specified</td></tr>", 1);
1275       if (!err) err = map_block_killer(exports, "have-filterfile");
1276    }
1277
1278 #ifdef FEATURE_TRUST
1279    if (csp->tlist)
1280    {
1281       if (!err) err = map(exports, "trust-filename", 1, html_encode(csp->tlist->filename), 0);
1282    }
1283    else
1284    {
1285       if (!err) err = map(exports, "trust-filename", 1, "None specified", 1);
1286       if (!err) err = map_block_killer(exports, "have-trustfile");
1287    }
1288 #else
1289    if (!err) err = map_block_killer(exports, "trust-support");
1290 #endif /* ndef FEATURE_TRUST */
1291
1292 #ifdef FEATURE_CGI_EDIT_ACTIONS
1293    if (!err && (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
1294    {
1295       err = map_block_killer(exports, "cgi-editor-is-disabled");
1296    }
1297 #endif /* ndef CGI_EDIT_ACTIONS */
1298
1299    if (err)
1300    {
1301       free_map(exports);
1302       return JB_ERR_MEMORY;
1303    }
1304
1305    return template_fill_for_cgi(csp, "show-status", exports, rsp);
1306 }
1307
1308  
1309 /*********************************************************************
1310  *
1311  * Function    :  cgi_show_url_info
1312  *
1313  * Description :  CGI function that determines and shows which actions
1314  *                Privoxy will perform for a given url, and which
1315  *                matches starting from the defaults have lead to that.
1316  *
1317  * Parameters  :
1318  *          1  :  csp = Current client state (buffers, headers, etc...)
1319  *          2  :  rsp = http_response data structure for output
1320  *          3  :  parameters = map of cgi parameters
1321  *
1322  * CGI Parameters :
1323  *            url : The url whose actions are to be determined.
1324  *                  If url is unset, the url-given conditional will be
1325  *                  set, so that all but the form can be suppressed in
1326  *                  the template.
1327  *
1328  * Returns     :  JB_ERR_OK on success
1329  *                JB_ERR_MEMORY on out-of-memory error.  
1330  *
1331  *********************************************************************/
1332 jb_err cgi_show_url_info(struct client_state *csp,
1333                          struct http_response *rsp,
1334                          const struct map *parameters)
1335 {
1336    char *url_param;
1337    struct map *exports;
1338    char buf[150];
1339
1340    assert(csp);
1341    assert(rsp);
1342    assert(parameters);
1343
1344    if (NULL == (exports = default_exports(csp, "show-url-info")))
1345    {
1346       return JB_ERR_MEMORY;
1347    }
1348
1349    /*
1350     * Get the url= parameter (if present) and remove any leading/trailing spaces.
1351     */
1352    url_param = strdup(lookup(parameters, "url"));
1353    if (url_param == NULL)
1354    {
1355       free_map(exports);
1356       return JB_ERR_MEMORY;
1357    }
1358    chomp(url_param);
1359
1360    /*
1361     * Handle prefixes.  4 possibilities:
1362     * 1) "http://" or "https://" prefix present and followed by URL - OK
1363     * 2) Only the "http://" or "https://" part is present, no URL - change
1364     *    to empty string so it will be detected later as "no URL".
1365     * 3) Parameter specified but doesn't contain "http(s?)://" - add a
1366     *    "http://" prefix.
1367     * 4) Parameter not specified or is empty string - let this fall through
1368     *    for now, next block of code will handle it.
1369     */
1370    if (0 == strncmp(url_param, "http://", 7))
1371    {
1372       if (url_param[7] == '\0')
1373       {
1374          /*
1375           * Empty URL (just prefix).
1376           * Make it totally empty so it's caught by the next if()
1377           */
1378          url_param[0] = '\0';
1379       }
1380    }
1381    else if (0 == strncmp(url_param, "https://", 8))
1382    {
1383       if (url_param[8] == '\0')
1384       {
1385          /*
1386           * Empty URL (just prefix).
1387           * Make it totally empty so it's caught by the next if()
1388           */
1389          url_param[0] = '\0';
1390       }
1391    }
1392    else if (url_param[0] != '\0')
1393    {
1394       /*
1395        * Unknown prefix - assume http://
1396        */
1397       const size_t url_param_prefixed_size = 7 + 1 + strlen(url_param);
1398       char * url_param_prefixed = malloc(url_param_prefixed_size);
1399       if (NULL == url_param_prefixed)
1400       {
1401          free(url_param);
1402          free_map(exports);
1403          return JB_ERR_MEMORY;
1404       }
1405       strlcpy(url_param_prefixed, "http://", url_param_prefixed_size);
1406       strlcat(url_param_prefixed, url_param, url_param_prefixed_size);
1407       free(url_param);
1408       url_param = url_param_prefixed;
1409    }
1410
1411    /*
1412     * Hide "toggle off" warning if Privoxy is toggled on.
1413     */
1414    if (
1415 #ifdef FEATURE_TOGGLE
1416        (global_toggle_state == 1) &&
1417 #endif /* def FEATURE_TOGGLE */
1418        map_block_killer(exports, "privoxy-is-toggled-off")
1419       )
1420    {
1421       free_map(exports);
1422       return JB_ERR_MEMORY;
1423    }
1424
1425    if (url_param[0] == '\0')
1426    {
1427       /* URL paramater not specified, display query form only. */
1428       free(url_param);
1429       if (map_block_killer(exports, "url-given")
1430         || map(exports, "url", 1, "", 1))
1431       {
1432          free_map(exports);
1433          return JB_ERR_MEMORY;
1434       }
1435    }
1436    else
1437    {
1438       /* Given a URL, so query it. */
1439       jb_err err;
1440       char *matches;
1441       char *s;
1442       int hits = 0;
1443       struct file_list *fl;
1444       struct url_actions *b;
1445       struct http_request url_to_query[1];
1446       struct current_action_spec action[1];
1447       int i;
1448       
1449       if (map(exports, "url", 1, html_encode(url_param), 0))
1450       {
1451          free(url_param);
1452          free_map(exports);
1453          return JB_ERR_MEMORY;
1454       }
1455
1456       init_current_action(action);
1457
1458       if (map(exports, "default", 1, current_action_to_html(csp, action), 0))
1459       {
1460          free_current_action(action);
1461          free(url_param);
1462          free_map(exports);
1463          return JB_ERR_MEMORY;
1464       }
1465
1466       err = parse_http_url(url_param, url_to_query, csp);
1467
1468       free(url_param);
1469
1470       if (err == JB_ERR_MEMORY)
1471       {
1472          free_http_request(url_to_query);
1473          free_current_action(action);
1474          free_map(exports);
1475          return JB_ERR_MEMORY;
1476       }
1477       else if (err)
1478       {
1479          /* Invalid URL */
1480
1481          err = map(exports, "matches", 1, "<b>[Invalid URL specified!]</b>" , 1);
1482          if (!err) err = map(exports, "final", 1, lookup(exports, "default"), 1);
1483          if (!err) err = map_block_killer(exports, "valid-url");
1484
1485          free_current_action(action);
1486          free_http_request(url_to_query);
1487
1488          if (err)
1489          {
1490             free_map(exports);
1491             return JB_ERR_MEMORY;
1492          }
1493
1494          return template_fill_for_cgi(csp, "show-url-info", exports, rsp);
1495       }
1496
1497       /*
1498        * We have a warning about SSL paths.  Hide it for unencrypted sites.
1499        */
1500       if (!url_to_query->ssl)
1501       {
1502          if (map_block_killer(exports, "https"))
1503          {
1504             free_current_action(action);
1505             free_map(exports);
1506             free_http_request(url_to_query);
1507             return JB_ERR_MEMORY;
1508          }
1509       }
1510
1511       matches = strdup("<table summary=\"\" class=\"transparent\">");
1512
1513       for (i = 0; i < MAX_AF_FILES; i++)
1514       {
1515          if (NULL == csp->config->actions_file_short[i]
1516              || !strcmp(csp->config->actions_file_short[i], "standard.action")) continue;
1517
1518          b = NULL;
1519          hits = 1;
1520          if ((fl = csp->actions_list[i]) != NULL)
1521          {
1522             if ((b = fl->f) != NULL)
1523             {
1524                /* FIXME: Hardcoded HTML! */
1525                string_append(&matches, "<tr><th>In file: ");
1526                string_join  (&matches, html_encode(csp->config->actions_file_short[i]));
1527                snprintf(buf, sizeof(buf), " <a class=\"cmd\" href=\"/show-status?file=actions&amp;index=%d\">", i);
1528                string_append(&matches, buf);
1529                string_append(&matches, "View</a>");
1530 #ifdef FEATURE_CGI_EDIT_ACTIONS
1531                if (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS)
1532                {
1533 #ifdef HAVE_ACCESS
1534                   if (access(csp->config->actions_file[i], W_OK) == 0)
1535                   {
1536 #endif /* def HAVE_ACCESS */
1537                      snprintf(buf, sizeof(buf),
1538                         " <a class=\"cmd\" href=\"/edit-actions-list?f=%d\">", i);
1539                      string_append(&matches, buf);
1540                      string_append(&matches, "Edit</a>");
1541 #ifdef HAVE_ACCESS
1542                   }
1543                   else
1544                   {
1545                      string_append(&matches, " <strong>No write access.</strong>");
1546                   }
1547 #endif /* def HAVE_ACCESS */
1548                }
1549 #endif /* FEATURE_CGI_EDIT_ACTIONS */
1550
1551                string_append(&matches, "</th></tr>\n");
1552
1553                hits = 0;
1554                b = b->next;
1555             }
1556          }
1557
1558          for (; (b != NULL) && (matches != NULL); b = b->next)
1559          {
1560             if (url_match(b->url, url_to_query))
1561             {
1562                string_append(&matches, "<tr><td>{");
1563                string_join  (&matches, actions_to_html(csp, b->action));
1564                string_append(&matches, " }<br>\n<code>");
1565                string_join  (&matches, html_encode(b->url->spec));
1566                string_append(&matches, "</code></td></tr>\n");
1567
1568                if (merge_current_action(action, b->action))
1569                {
1570                   freez(matches);
1571                   free_http_request(url_to_query);
1572                   free_current_action(action);
1573                   free_map(exports);
1574                   return JB_ERR_MEMORY;
1575                }
1576                hits++;
1577             }
1578          }
1579
1580          if (!hits)
1581          {
1582             string_append(&matches, "<tr><td>(no matches in this file)</td></tr>\n");
1583          }
1584       }
1585       string_append(&matches, "</table>\n");
1586
1587       /*
1588        * XXX: Kludge to make sure the "Forward settings" section
1589        * shows what forward-override{} would do with the requested URL.
1590        * No one really cares how the CGI request would be forwarded
1591        * if it wasn't intercepted as CGI request in the first place.
1592        *
1593        * From here on the action bitmask will no longer reflect
1594        * the real url (http://config.privoxy.org/show-url-info?url=.*),
1595        * but luckily it's no longer required later on anyway.
1596        */
1597       free_current_action(csp->action);
1598       get_url_actions(csp, url_to_query);
1599
1600       /*
1601        * Fill in forwarding settings.
1602        *
1603        * The possibilities are:
1604        *  - no forwarding
1605        *  - http forwarding only
1606        *  - socks4(a) forwarding only
1607        *  - socks4(a) and http forwarding.
1608        *
1609        * XXX: Parts of this code could be reused for the
1610        * "forwarding-failed" template which currently doesn't
1611        * display the proxy port and an eventual second forwarder.
1612        */
1613       {
1614          const struct forward_spec *fwd = forward_url(csp, url_to_query);
1615
1616          if ((fwd->gateway_host == NULL) && (fwd->forward_host == NULL))
1617          {
1618             if (!err) err = map_block_killer(exports, "socks-forwarder");
1619             if (!err) err = map_block_killer(exports, "http-forwarder");
1620          }
1621          else
1622          {
1623             char port[10]; /* We save proxy ports as int but need a string here */
1624
1625             if (!err) err = map_block_killer(exports, "no-forwarder");
1626
1627             if (fwd->gateway_host != NULL)
1628             {
1629                char *socks_type = NULL;
1630
1631                switch (fwd->type)
1632                {
1633                   case SOCKS_4:
1634                      socks_type = "socks4";
1635                      break;
1636                   case SOCKS_4A:
1637                      socks_type = "socks4a";
1638                      break;
1639                   case SOCKS_5:
1640                      socks_type = "socks5";
1641                      break;
1642                   default:
1643                      log_error(LOG_LEVEL_FATAL, "Unknown socks type: %d.", fwd->type);
1644                }
1645
1646                if (!err) err = map(exports, "socks-type", 1, socks_type, 1);
1647                if (!err) err = map(exports, "gateway-host", 1, fwd->gateway_host, 1);
1648                snprintf(port, sizeof(port), "%d", fwd->gateway_port);
1649                if (!err) err = map(exports, "gateway-port", 1, port, 1);
1650             }
1651             else
1652             {
1653                if (!err) err = map_block_killer(exports, "socks-forwarder");
1654             }
1655
1656             if (fwd->forward_host != NULL)
1657             {
1658                if (!err) err = map(exports, "forward-host", 1, fwd->forward_host, 1);
1659                snprintf(port, sizeof(port), "%d", fwd->forward_port);
1660                if (!err) err = map(exports, "forward-port", 1, port, 1);
1661             }
1662             else
1663             {
1664                if (!err) err = map_block_killer(exports, "http-forwarder");
1665             }
1666          }
1667       }
1668
1669       free_http_request(url_to_query);
1670
1671       if (err || matches == NULL)
1672       {
1673          free_current_action(action);
1674          free_map(exports);
1675          return JB_ERR_MEMORY;
1676       }
1677
1678 #ifdef FEATURE_CGI_EDIT_ACTIONS
1679       if ((csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
1680       {
1681          err = map_block_killer(exports, "cgi-editor-is-disabled");
1682       }
1683 #endif /* FEATURE_CGI_EDIT_ACTIONS */
1684
1685       if (err || map(exports, "matches", 1, matches , 0))
1686       {
1687          free_current_action(action);
1688          free_map(exports);
1689          return JB_ERR_MEMORY;
1690       }
1691
1692       s = current_action_to_html(csp, action);
1693
1694       free_current_action(action);
1695
1696       if (map(exports, "final", 1, s, 0))
1697       {
1698          free_map(exports);
1699          return JB_ERR_MEMORY;
1700       }
1701    }
1702
1703    return template_fill_for_cgi(csp, "show-url-info", exports, rsp);
1704 }
1705
1706
1707 /*********************************************************************
1708  *
1709  * Function    :  cgi_robots_txt
1710  *
1711  * Description :  CGI function to return "/robots.txt".
1712  *
1713  * Parameters  :
1714  *          1  :  csp = Current client state (buffers, headers, etc...)
1715  *          2  :  rsp = http_response data structure for output
1716  *          3  :  parameters = map of cgi parameters
1717  *
1718  * CGI Parameters : None
1719  *
1720  * Returns     :  JB_ERR_OK on success
1721  *                JB_ERR_MEMORY on out-of-memory error.  
1722  *
1723  *********************************************************************/
1724 jb_err cgi_robots_txt(struct client_state *csp,
1725                       struct http_response *rsp,
1726                       const struct map *parameters)
1727 {
1728    char buf[100];
1729    jb_err err;
1730
1731    rsp->body = strdup(
1732       "# This is the Privoxy control interface.\n"
1733       "# It isn't very useful to index it, and you're likely to break stuff.\n"
1734       "# So go away!\n"
1735       "\n"
1736       "User-agent: *\n"
1737       "Disallow: /\n"
1738       "\n");
1739    if (rsp->body == NULL)
1740    {
1741       return JB_ERR_MEMORY;
1742    }
1743
1744    err = enlist_unique(rsp->headers, "Content-Type: text/plain", 13);
1745
1746    rsp->is_static = 1;
1747
1748    get_http_time(7 * 24 * 60 * 60, buf, sizeof(buf)); /* 7 days into future */
1749    if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1750
1751    return (err ? JB_ERR_MEMORY : JB_ERR_OK);
1752 }
1753
1754
1755 /*********************************************************************
1756  *
1757  * Function    :  show_defines
1758  *
1759  * Description :  Add to a map the state od all conditional #defines
1760  *                used when building
1761  *
1762  * Parameters  :
1763  *          1  :  exports = map to extend
1764  *
1765  * Returns     :  JB_ERR_OK on success
1766  *                JB_ERR_MEMORY on out-of-memory error.  
1767  *
1768  *********************************************************************/
1769 static jb_err show_defines(struct map *exports)
1770 {
1771    jb_err err = JB_ERR_OK;
1772
1773 #ifdef FEATURE_ACL
1774    if (!err) err = map_conditional(exports, "FEATURE_ACL", 1);
1775 #else /* ifndef FEATURE_ACL */
1776    if (!err) err = map_conditional(exports, "FEATURE_ACL", 0);
1777 #endif /* ndef FEATURE_ACL */
1778
1779 #ifdef FEATURE_CGI_EDIT_ACTIONS
1780    if (!err) err = map_conditional(exports, "FEATURE_CGI_EDIT_ACTIONS", 1);
1781 #else /* ifndef FEATURE_COOKIE_JAR */
1782    if (!err) err = map_conditional(exports, "FEATURE_CGI_EDIT_ACTIONS", 0);
1783 #endif /* ndef FEATURE_COOKIE_JAR */
1784
1785 #ifdef FEATURE_COOKIE_JAR
1786    if (!err) err = map_conditional(exports, "FEATURE_COOKIE_JAR", 1);
1787 #else /* ifndef FEATURE_COOKIE_JAR */
1788    if (!err) err = map_conditional(exports, "FEATURE_COOKIE_JAR", 0);
1789 #endif /* ndef FEATURE_COOKIE_JAR */
1790
1791 #ifdef FEATURE_FAST_REDIRECTS
1792    if (!err) err = map_conditional(exports, "FEATURE_FAST_REDIRECTS", 1);
1793 #else /* ifndef FEATURE_FAST_REDIRECTS */
1794    if (!err) err = map_conditional(exports, "FEATURE_FAST_REDIRECTS", 0);
1795 #endif /* ndef FEATURE_FAST_REDIRECTS */
1796
1797 #ifdef FEATURE_FORCE_LOAD
1798    if (!err) err = map_conditional(exports, "FEATURE_FORCE_LOAD", 1);
1799    if (!err) err = map(exports, "FORCE_PREFIX", 1, FORCE_PREFIX, 1);
1800 #else /* ifndef FEATURE_FORCE_LOAD */
1801    if (!err) err = map_conditional(exports, "FEATURE_FORCE_LOAD", 0);
1802    if (!err) err = map(exports, "FORCE_PREFIX", 1, "(none - disabled)", 1);
1803 #endif /* ndef FEATURE_FORCE_LOAD */
1804
1805 #ifdef FEATURE_GRACEFUL_TERMINATION
1806    if (!err) err = map_conditional(exports, "FEATURE_GRACEFUL_TERMINATION", 1);
1807 #else /* ifndef FEATURE_GRACEFUL_TERMINATION */
1808    if (!err) err = map_conditional(exports, "FEATURE_GRACEFUL_TERMINATION", 0);
1809 #endif /* ndef FEATURE_GRACEFUL_TERMINATION */
1810
1811 #ifdef FEATURE_IMAGE_BLOCKING
1812    if (!err) err = map_conditional(exports, "FEATURE_IMAGE_BLOCKING", 1);
1813 #else /* ifndef FEATURE_IMAGE_BLOCKING */
1814    if (!err) err = map_conditional(exports, "FEATURE_IMAGE_BLOCKING", 0);
1815 #endif /* ndef FEATURE_IMAGE_BLOCKING */
1816
1817 #ifdef FEATURE_IMAGE_DETECT_MSIE
1818    if (!err) err = map_conditional(exports, "FEATURE_IMAGE_DETECT_MSIE", 1);
1819 #else /* ifndef FEATURE_IMAGE_DETECT_MSIE */
1820    if (!err) err = map_conditional(exports, "FEATURE_IMAGE_DETECT_MSIE", 0);
1821 #endif /* ndef FEATURE_IMAGE_DETECT_MSIE */
1822
1823 #ifdef FEATURE_NO_GIFS
1824    if (!err) err = map_conditional(exports, "FEATURE_NO_GIFS", 1);
1825 #else /* ifndef FEATURE_NO_GIFS */
1826    if (!err) err = map_conditional(exports, "FEATURE_NO_GIFS", 0);
1827 #endif /* ndef FEATURE_NO_GIFS */
1828
1829 #ifdef FEATURE_PTHREAD
1830    if (!err) err = map_conditional(exports, "FEATURE_PTHREAD", 1);
1831 #else /* ifndef FEATURE_PTHREAD */
1832    if (!err) err = map_conditional(exports, "FEATURE_PTHREAD", 0);
1833 #endif /* ndef FEATURE_PTHREAD */
1834
1835 #ifdef FEATURE_STATISTICS
1836    if (!err) err = map_conditional(exports, "FEATURE_STATISTICS", 1);
1837 #else /* ifndef FEATURE_STATISTICS */
1838    if (!err) err = map_conditional(exports, "FEATURE_STATISTICS", 0);
1839 #endif /* ndef FEATURE_STATISTICS */
1840
1841 #ifdef FEATURE_TOGGLE
1842    if (!err) err = map_conditional(exports, "FEATURE_TOGGLE", 1);
1843 #else /* ifndef FEATURE_TOGGLE */
1844    if (!err) err = map_conditional(exports, "FEATURE_TOGGLE", 0);
1845 #endif /* ndef FEATURE_TOGGLE */
1846
1847 #ifdef FEATURE_TRUST
1848    if (!err) err = map_conditional(exports, "FEATURE_TRUST", 1);
1849 #else /* ifndef FEATURE_TRUST */
1850    if (!err) err = map_conditional(exports, "FEATURE_TRUST", 0);
1851 #endif /* ndef FEATURE_TRUST */
1852
1853 #ifdef FEATURE_ZLIB
1854    if (!err) err = map_conditional(exports, "FEATURE_ZLIB", 1);
1855 #else /* ifndef FEATURE_ZLIB */
1856    if (!err) err = map_conditional(exports, "FEATURE_ZLIB", 0);
1857 #endif /* ndef FEATURE_ZLIB */
1858
1859 #ifdef STATIC_PCRE
1860    if (!err) err = map_conditional(exports, "STATIC_PCRE", 1);
1861 #else /* ifndef STATIC_PCRE */
1862    if (!err) err = map_conditional(exports, "STATIC_PCRE", 0);
1863 #endif /* ndef STATIC_PCRE */
1864
1865 #ifdef STATIC_PCRS
1866    if (!err) err = map_conditional(exports, "STATIC_PCRS", 1);
1867 #else /* ifndef STATIC_PCRS */
1868    if (!err) err = map_conditional(exports, "STATIC_PCRS", 0);
1869 #endif /* ndef STATIC_PCRS */
1870
1871    return err;
1872 }
1873
1874
1875 /*********************************************************************
1876  *
1877  * Function    :  show_rcs
1878  *
1879  * Description :  Create a string with the rcs info for all sourcefiles
1880  *
1881  * Parameters  :  None
1882  *
1883  * Returns     :  A string, or NULL on out-of-memory.
1884  *
1885  *********************************************************************/
1886 static char *show_rcs(void)
1887 {
1888    char *result = strdup("");
1889    char buf[BUFFER_SIZE];
1890
1891    /* Instead of including *all* dot h's in the project (thus creating a
1892     * tremendous amount of dependencies), I will concede to declaring them
1893     * as extern's.  This forces the developer to add to this list, but oh well.
1894     */
1895
1896 #define SHOW_RCS(__x)              \
1897    {                               \
1898       extern const char __x[];     \
1899       snprintf(buf, sizeof(buf), " %s\n", __x);   \
1900       string_append(&result, buf); \
1901    }
1902
1903    /* In alphabetical order */
1904    SHOW_RCS(actions_h_rcs)
1905    SHOW_RCS(actions_rcs)
1906 #ifdef AMIGA
1907    SHOW_RCS(amiga_h_rcs)
1908    SHOW_RCS(amiga_rcs)
1909 #endif /* def AMIGA */
1910    SHOW_RCS(cgi_h_rcs)
1911    SHOW_RCS(cgi_rcs)
1912 #ifdef FEATURE_CGI_EDIT_ACTIONS
1913    SHOW_RCS(cgiedit_h_rcs)
1914    SHOW_RCS(cgiedit_rcs)
1915 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
1916    SHOW_RCS(cgisimple_h_rcs)
1917    SHOW_RCS(cgisimple_rcs)
1918 #ifdef __MINGW32__
1919    SHOW_RCS(cygwin_h_rcs)
1920 #endif
1921    SHOW_RCS(deanimate_h_rcs)
1922    SHOW_RCS(deanimate_rcs)
1923    SHOW_RCS(encode_h_rcs)
1924    SHOW_RCS(encode_rcs)
1925    SHOW_RCS(errlog_h_rcs)
1926    SHOW_RCS(errlog_rcs)
1927    SHOW_RCS(filters_h_rcs)
1928    SHOW_RCS(filters_rcs)
1929    SHOW_RCS(gateway_h_rcs)
1930    SHOW_RCS(gateway_rcs)
1931    SHOW_RCS(jbsockets_h_rcs)
1932    SHOW_RCS(jbsockets_rcs)
1933    SHOW_RCS(jcc_h_rcs)
1934    SHOW_RCS(jcc_rcs)
1935    SHOW_RCS(list_h_rcs)
1936    SHOW_RCS(list_rcs)
1937    SHOW_RCS(loadcfg_h_rcs)
1938    SHOW_RCS(loadcfg_rcs)
1939    SHOW_RCS(loaders_h_rcs)
1940    SHOW_RCS(loaders_rcs)
1941    SHOW_RCS(miscutil_h_rcs)
1942    SHOW_RCS(miscutil_rcs)
1943    SHOW_RCS(parsers_h_rcs)
1944    SHOW_RCS(parsers_rcs)
1945    SHOW_RCS(pcrs_rcs)
1946    SHOW_RCS(pcrs_h_rcs)
1947    SHOW_RCS(project_h_rcs)
1948    SHOW_RCS(ssplit_h_rcs)
1949    SHOW_RCS(ssplit_rcs)
1950    SHOW_RCS(urlmatch_h_rcs)
1951    SHOW_RCS(urlmatch_rcs)
1952 #ifdef _WIN32
1953 #ifndef _WIN_CONSOLE
1954    SHOW_RCS(w32log_h_rcs)
1955    SHOW_RCS(w32log_rcs)
1956    SHOW_RCS(w32res_h_rcs)
1957    SHOW_RCS(w32taskbar_h_rcs)
1958    SHOW_RCS(w32taskbar_rcs)
1959 #endif /* ndef _WIN_CONSOLE */
1960    SHOW_RCS(win32_h_rcs)
1961    SHOW_RCS(win32_rcs)
1962 #endif /* def _WIN32 */
1963
1964 #undef SHOW_RCS
1965
1966    return result;
1967
1968 }
1969
1970
1971 /*********************************************************************
1972  *
1973  * Function    :  cgi_show_file
1974  *
1975  * Description :  CGI function that shows the content of a
1976  *                configuration file.
1977  *
1978  * Parameters  :
1979  *          1  :  csp = Current client state (buffers, headers, etc...)
1980  *          2  :  rsp = http_response data structure for output
1981  *          3  :  parameters = map of cgi parameters
1982  *
1983  * CGI Parameters :
1984  *        file :  Which file to show.  Only first letter is checked,
1985  *                valid values are:
1986  *                - "a"ction file
1987  *                - "r"egex
1988  *                - "t"rust
1989  *                Default is to show menu and other information.
1990  *
1991  * Returns     :  JB_ERR_OK on success
1992  *                JB_ERR_MEMORY on out-of-memory error.  
1993  *
1994  *********************************************************************/
1995 static jb_err cgi_show_file(struct client_state *csp,
1996                             struct http_response *rsp,
1997                             const struct map *parameters)
1998 {
1999    unsigned i;
2000    const char * filename = NULL;
2001    char * file_description = NULL;
2002
2003    assert(csp);
2004    assert(rsp);
2005    assert(parameters);
2006
2007    switch (*(lookup(parameters, "file")))
2008    {
2009    case 'a':
2010       if (!get_number_param(csp, parameters, "index", &i) && i < MAX_AF_FILES && csp->actions_list[i])
2011       {
2012          filename = csp->actions_list[i]->filename;
2013          file_description = "Actions File";
2014       }
2015       break;
2016
2017    case 'f':
2018       if (!get_number_param(csp, parameters, "index", &i) && i < MAX_AF_FILES && csp->rlist[i])
2019       {
2020          filename = csp->rlist[i]->filename;
2021          file_description = "Filter File";
2022       }
2023       break;
2024
2025 #ifdef FEATURE_TRUST
2026    case 't':
2027       if (csp->tlist)
2028       {
2029          filename = csp->tlist->filename;
2030          file_description = "Trust File";
2031       }
2032       break;
2033 #endif /* def FEATURE_TRUST */
2034    }
2035
2036    if (NULL != filename)
2037    {
2038       struct map *exports;
2039       char *s;
2040       FILE * fp;
2041
2042       exports = default_exports(csp, "show-status");
2043       if (NULL == exports)
2044       {
2045          return JB_ERR_MEMORY;
2046       }
2047
2048       if ( map(exports, "file-description", 1, file_description, 1)
2049         || map(exports, "filepath", 1, html_encode(filename), 0) )
2050       {
2051          free_map(exports);
2052          return JB_ERR_MEMORY;
2053       }
2054
2055       if ((fp = fopen(filename, "rb")) == NULL)
2056       {
2057          if (map(exports, "content", 1, "<h1>ERROR OPENING FILE!</h1>", 1))
2058          {
2059             free_map(exports);
2060             return JB_ERR_MEMORY;
2061          }
2062       }
2063       else
2064       {
2065          /*
2066           * XXX: this code is "quite similar" to the one
2067           * in cgi_send_user_manual() and should be refactored.
2068           * While at it, the return codes for ftell() and fseek
2069           * should be verified.
2070           */
2071          size_t length;
2072          /* Get file length */
2073          fseek(fp, 0, SEEK_END);
2074          length = (size_t)ftell(fp);
2075          fseek(fp, 0, SEEK_SET);
2076
2077          s = (char *)zalloc(length+1);
2078          if (NULL == s)
2079          {
2080             fclose(fp);
2081             return JB_ERR_MEMORY;
2082          }
2083          if (!fread(s, length, 1, fp))
2084          {
2085             /*
2086              * May happen if the file size changes between fseek() and fread().
2087              * If it does, we just log it and serve what we got.
2088              */
2089             log_error(LOG_LEVEL_ERROR, "Couldn't completely read file %s.", filename);
2090          }
2091          fclose(fp);
2092
2093          s = html_encode_and_free_original(s);
2094          if (NULL == s)
2095          {
2096             return JB_ERR_MEMORY;
2097          }
2098
2099          if (map(exports, "contents", 1, s, 0))
2100          {
2101             free_map(exports);
2102             return JB_ERR_MEMORY;
2103          }
2104       }
2105
2106       return template_fill_for_cgi(csp, "show-status-file", exports, rsp);
2107    }
2108
2109    /*
2110     * XXX: should return JB_ERR_PARSE but CGI handlers
2111     * currently aren't expected to do that.
2112     */
2113    return JB_ERR_OK;
2114 }
2115  
2116
2117 /*
2118   Local Variables:
2119   tab-width: 3
2120   end:
2121 */