Bump copyright
[privoxy.git] / cgisimple.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/cgisimple.c,v $
4  *
5  * Purpose     :  Simple CGIs to get information about Privoxy's
6  *                status.
7  *
8  * Copyright   :  Written by and Copyright (C) 2001-2021 the
9  *                Privoxy team. https://www.privoxy.org/
10  *
11  *                Based on the Internet Junkbuster originally written
12  *                by and Copyright (C) 1997 Anonymous Coders and
13  *                Junkbusters Corporation.  http://www.junkbusters.com
14  *
15  *                This program is free software; you can redistribute it
16  *                and/or modify it under the terms of the GNU General
17  *                Public License as published by the Free Software
18  *                Foundation; either version 2 of the License, or (at
19  *                your option) any later version.
20  *
21  *                This program is distributed in the hope that it will
22  *                be useful, but WITHOUT ANY WARRANTY; without even the
23  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
24  *                PARTICULAR PURPOSE.  See the GNU General Public
25  *                License for more details.
26  *
27  *                The GNU General Public License should be included with
28  *                this file.  If not, you can view it at
29  *                http://www.gnu.org/copyleft/gpl.html
30  *                or write to the Free Software Foundation, Inc., 59
31  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
32  *
33  **********************************************************************/
34
35
36 #include "config.h"
37
38 #include <stdio.h>
39 #include <sys/types.h>
40 #include <stdlib.h>
41 #include <ctype.h>
42 #include <string.h>
43 #include <assert.h>
44
45 #if defined (HAVE_ACCESS) && defined (HAVE_UNISTD_H)
46 #include <unistd.h>
47 #endif /* def HAVE_ACCESS && HAVE_UNISTD_H */
48
49 #include "project.h"
50 #include "cgi.h"
51 #include "cgisimple.h"
52 #include "list.h"
53 #include "encode.h"
54 #include "jcc.h"
55 #include "filters.h"
56 #include "actions.h"
57 #include "miscutil.h"
58 #include "loadcfg.h"
59 #include "parsers.h"
60 #include "urlmatch.h"
61 #include "errlog.h"
62 #ifdef FEATURE_CLIENT_TAGS
63 #include "client-tags.h"
64 #endif
65
66 static jb_err show_defines(struct map *exports);
67 static jb_err cgi_show_file(struct client_state *csp,
68                             struct http_response *rsp,
69                             const struct map *parameters);
70 static jb_err load_file(const char *filename, char **buffer, size_t *length);
71
72 /*********************************************************************
73  *
74  * Function    :  cgi_default
75  *
76  * Description :  CGI function that is called for the CGI_SITE_1_HOST
77  *                and CGI_SITE_2_HOST/CGI_SITE_2_PATH base URLs.
78  *                Boring - only exports the default exports.
79  *
80  * Parameters  :
81  *          1  :  csp = Current client state (buffers, headers, etc...)
82  *          2  :  rsp = http_response data structure for output
83  *          3  :  parameters = map of cgi parameters
84  *
85  * CGI Parameters : none
86  *
87  * Returns     :  JB_ERR_OK on success
88  *                JB_ERR_MEMORY on out-of-memory
89  *
90  *********************************************************************/
91 jb_err cgi_default(struct client_state *csp,
92                    struct http_response *rsp,
93                    const struct map *parameters)
94 {
95    struct map *exports;
96
97    (void)parameters;
98
99    assert(csp);
100    assert(rsp);
101
102    if (NULL == (exports = default_exports(csp, "")))
103    {
104       return JB_ERR_MEMORY;
105    }
106
107    return template_fill_for_cgi(csp, "default", exports, rsp);
108 }
109
110
111 /*********************************************************************
112  *
113  * Function    :  cgi_error_404
114  *
115  * Description :  CGI function that is called if an unknown action was
116  *                given.
117  *
118  * Parameters  :
119  *          1  :  csp = Current client state (buffers, headers, etc...)
120  *          2  :  rsp = http_response data structure for output
121  *          3  :  parameters = map of cgi parameters
122  *
123  * CGI Parameters : none
124  *
125  * Returns     :  JB_ERR_OK on success
126  *                JB_ERR_MEMORY on out-of-memory error.
127  *
128  *********************************************************************/
129 jb_err cgi_error_404(struct client_state *csp,
130                      struct http_response *rsp,
131                      const struct map *parameters)
132 {
133    struct map *exports;
134
135    assert(csp);
136    assert(rsp);
137    assert(parameters);
138
139    if (NULL == (exports = default_exports(csp, NULL)))
140    {
141       return JB_ERR_MEMORY;
142    }
143
144    rsp->status = strdup_or_die("404 Privoxy configuration page not found");
145
146    return template_fill_for_cgi(csp, "cgi-error-404", exports, rsp);
147 }
148
149
150 #ifdef FEATURE_GRACEFUL_TERMINATION
151 /*********************************************************************
152  *
153  * Function    :  cgi_die
154  *
155  * Description :  CGI function to shut down Privoxy.
156  *                NOTE: Turning this on in a production build
157  *                would be a BAD idea.  An EXTREMELY BAD idea.
158  *                In short, don't do it.
159  *
160  * Parameters  :
161  *          1  :  csp = Current client state (buffers, headers, etc...)
162  *          2  :  rsp = http_response data structure for output
163  *          3  :  parameters = map of cgi parameters
164  *
165  * CGI Parameters : none
166  *
167  * Returns     :  JB_ERR_OK on success
168  *
169  *********************************************************************/
170 jb_err cgi_die (struct client_state *csp,
171                 struct http_response *rsp,
172                 const struct map *parameters)
173 {
174    static const char status[] = "200 OK Privoxy shutdown request received";
175    static const char body[] =
176       "<html>\n"
177       "<head>\n"
178       " <title>Privoxy shutdown request received</title>\n"
179       " <link rel=\"shortcut icon\" href=\"" CGI_PREFIX "error-favicon.ico\" type=\"image/x-icon\">\n"
180       " <link rel=\"stylesheet\" type=\"text/css\" href=\"" CGI_PREFIX "send-stylesheet\">\n"
181       "</head>\n"
182       "<body>\n"
183       "<h1>Privoxy shutdown request received</h1>\n"
184       "<p>Privoxy is going to shut down after the next request.</p>\n"
185       "</body>\n"
186       "</html>\n";
187
188    assert(csp);
189    assert(rsp);
190    assert(parameters);
191
192    /* quit */
193    g_terminate = 1;
194
195    csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
196
197    rsp->content_length = 0;
198    rsp->head_length = 0;
199    rsp->is_static = 0;
200
201    rsp->body = strdup_or_die(body);
202    rsp->status = strdup_or_die(status);
203
204    return JB_ERR_OK;
205 }
206 #endif /* def FEATURE_GRACEFUL_TERMINATION */
207
208
209 /*********************************************************************
210  *
211  * Function    :  cgi_show_request
212  *
213  * Description :  Show the client's request and what sed() would have
214  *                made of it.
215  *
216  * Parameters  :
217  *          1  :  csp = Current client state (buffers, headers, etc...)
218  *          2  :  rsp = http_response data structure for output
219  *          3  :  parameters = map of cgi parameters
220  *
221  * CGI Parameters : none
222  *
223  * Returns     :  JB_ERR_OK on success
224  *                JB_ERR_MEMORY on out-of-memory error.
225  *
226  *********************************************************************/
227 jb_err cgi_show_request(struct client_state *csp,
228                         struct http_response *rsp,
229                         const struct map *parameters)
230 {
231    char *p;
232    struct map *exports;
233
234    assert(csp);
235    assert(rsp);
236    assert(parameters);
237
238    if (NULL == (exports = default_exports(csp, "show-request")))
239    {
240       return JB_ERR_MEMORY;
241    }
242
243    /*
244     * Repair the damage done to the IOB by get_header()
245     */
246    for (p = csp->client_iob->buf; p < csp->client_iob->cur; p++)
247    {
248       if (*p == '\0') *p = '\n';
249    }
250
251    /*
252     * Export the original client's request and the one we would
253     * be sending to the server if this wasn't a CGI call
254     */
255
256    if (map(exports, "client-request", 1, html_encode(csp->client_iob->buf), 0))
257    {
258       free_map(exports);
259       return JB_ERR_MEMORY;
260    }
261
262    if (map(exports, "processed-request", 1,
263          html_encode_and_free_original(
264 #ifdef FEATURE_HTTPS_INSPECTION
265                                        csp->http->ssl ?
266                                        list_to_text(csp->https_headers) :
267 #endif
268                                        list_to_text(csp->headers)
269                                        ), 0))
270    {
271       free_map(exports);
272       return JB_ERR_MEMORY;
273    }
274
275    return template_fill_for_cgi(csp, "show-request", exports, rsp);
276 }
277
278
279 #ifdef FEATURE_CLIENT_TAGS
280 /*********************************************************************
281  *
282  * Function    :  cgi_create_client_tag_form
283  *
284  * Description :  Creates a HTML form to enable or disable a given
285  *                client tag.
286  *                XXX: Could use a template.
287  *
288  * Parameters  :
289  *          1  :  form = Buffer to fill with the generated form
290  *          2  :  size = Size of the form buffer
291  *          3  :  tag = Name of the tag this form should affect
292  *          4  :  toggle_state = Desired state after the button pressed 0
293  *          5  :  expires = Whether or not the tag should be enabled.
294  *                          Only checked if toggle_state is 1.
295  *
296  * Returns     :  void
297  *
298  *********************************************************************/
299 static void cgi_create_client_tag_form(char *form, size_t size,
300    const char *tag, int toggle_state, int expires)
301 {
302    char *button_name;
303
304    if (toggle_state == 1)
305    {
306       button_name = (expires == 1) ? "Enable" : "Enable temporarily";
307    }
308    else
309    {
310       assert(toggle_state == 0);
311       button_name = "Disable";
312    }
313
314    snprintf(form, size,
315       "<form method=\"GET\" action=\""CGI_PREFIX"toggle-client-tag\" style=\"display: inline\">\n"
316       " <input type=\"hidden\" name=\"tag\" value=\"%s\">\n"
317       " <input type=\"hidden\" name=\"toggle-state\" value=\"%i\">\n"
318       " <input type=\"hidden\" name=\"expires\" value=\"%u\">\n"
319       " <input type=\"submit\" value=\"%s\">\n"
320       "</form>", tag, toggle_state, !expires, button_name);
321 }
322
323 /*********************************************************************
324  *
325  * Function    :  cgi_show_client_tags
326  *
327  * Description :  Shows the tags that can be set based on the client
328  *                address (opt-in).
329  *
330  * Parameters  :
331  *          1  :  csp = Current client state (buffers, headers, etc...)
332  *          2  :  rsp = http_response data structure for output
333  *          3  :  parameters = map of cgi parameters
334  *
335  * CGI Parameters : none
336  *
337  * Returns     :  JB_ERR_OK on success
338  *                JB_ERR_MEMORY on out-of-memory error.
339  *
340  *********************************************************************/
341 jb_err cgi_show_client_tags(struct client_state *csp,
342                         struct http_response *rsp,
343                         const struct map *parameters)
344 {
345    struct map *exports;
346    struct client_tag_spec *this_tag;
347    jb_err err = JB_ERR_OK;
348    char *client_tag_status;
349    char buf[1000];
350    time_t refresh_delay;
351
352    assert(csp);
353    assert(rsp);
354    assert(parameters);
355
356    if (NULL == (exports = default_exports(csp, "client-tags")))
357    {
358       return JB_ERR_MEMORY;
359    }
360    assert(csp->client_address != NULL);
361
362    this_tag = csp->config->client_tags;
363    if (this_tag->name == NULL)
364    {
365       client_tag_status = strdup_or_die("<p>No tags have been configured.</p>\n");
366    }
367    else
368    {
369       client_tag_status = strdup_or_die("<table border=\"1\">\n"
370          "<tr><th>Tag name</th>\n"
371          "<th>Current state</th><th>Change state</th><th>Description</th></tr>\n");
372       while ((this_tag != NULL) && (this_tag->name != NULL))
373       {
374          int tag_state;
375
376          privoxy_mutex_lock(&client_tags_mutex);
377          tag_state = client_has_requested_tag(csp->client_address, this_tag->name);
378          privoxy_mutex_unlock(&client_tags_mutex);
379          if (!err) err = string_append(&client_tag_status, "<tr><td>");
380          if (!err) err = string_append(&client_tag_status, this_tag->name);
381          if (!err) err = string_append(&client_tag_status, "</td><td>");
382          if (!err) err = string_append(&client_tag_status, tag_state == 1 ? "Enabled" : "Disabled");
383          if (!err) err = string_append(&client_tag_status, "</td><td>");
384          cgi_create_client_tag_form(buf, sizeof(buf), this_tag->name, !tag_state, 1);
385          if (!err) err = string_append(&client_tag_status, buf);
386          if (tag_state == 0)
387          {
388             cgi_create_client_tag_form(buf, sizeof(buf), this_tag->name, !tag_state, 0);
389             if (!err) err = string_append(&client_tag_status, buf);
390          }
391          if (!err) err = string_append(&client_tag_status, "</td><td>");
392          if (!err) err = string_append(&client_tag_status, this_tag->description);
393          if (!err) err = string_append(&client_tag_status, "</td></tr>\n");
394          if (err)
395          {
396             break;
397          }
398          this_tag = this_tag->next;
399       }
400       if (!err) err = string_append(&client_tag_status, "</table>\n");
401       if (err)
402       {
403          free_map(exports);
404          return JB_ERR_MEMORY;
405       }
406    }
407    refresh_delay = get_next_tag_timeout_for_client(csp->client_address);
408    if (refresh_delay != 0)
409    {
410       snprintf(buf, sizeof(buf), "%u", csp->config->client_tag_lifetime);
411       if (map(exports, "refresh-delay", 1, buf, 1))
412       {
413          freez(client_tag_status);
414          free_map(exports);
415          return JB_ERR_MEMORY;
416       }
417    }
418    else
419    {
420       err = map_block_killer(exports, "tags-expire");
421       if (err != JB_ERR_OK)
422       {
423          freez(client_tag_status);
424          return err;
425       }
426    }
427
428    if (map(exports, "client-tags", 1, client_tag_status, 0))
429    {
430       free_map(exports);
431       return JB_ERR_MEMORY;
432    }
433
434    if (map(exports, "client-ip-addr", 1, csp->client_address, 1))
435    {
436       free_map(exports);
437       return JB_ERR_MEMORY;
438    }
439
440    return template_fill_for_cgi(csp, "client-tags", exports, rsp);
441 }
442
443
444 /*********************************************************************
445  *
446  * Function    :  cgi_toggle_client_tag
447  *
448  * Description :  Toggles a client tag and redirects to the show-tags
449  *                page
450  *
451  * Parameters  :
452  *          1  :  csp = Current client state (buffers, headers, etc...)
453  *          2  :  rsp = http_response data structure for output
454  *          3  :  parameters = map of cgi parameters
455  *
456  * CGI Parameters : none
457  *          1  :  tag = Name of the tag to enable or disable
458  *          2  :  toggle-state = How to toggle the tag (0/1)
459  *          3  :  expires = Set to 1 if the tag should be enabled
460  *                          temporarily, otherwise set to 0
461  *
462  * Returns     :  JB_ERR_OK on success
463  *                JB_ERR_MEMORY on out-of-memory error.
464  *
465  *********************************************************************/
466 jb_err cgi_toggle_client_tag(struct client_state *csp,
467                              struct http_response *rsp,
468                              const struct map *parameters)
469 {
470    const char *toggled_tag;
471    const char *toggle_state;
472    const char *tag_expires;
473    time_t time_to_live;
474
475    assert(csp);
476    assert(rsp);
477    assert(parameters);
478
479    toggled_tag = lookup(parameters, "tag");
480    if (*toggled_tag == '\0')
481    {
482       log_error(LOG_LEVEL_ERROR, "Received tag toggle request without tag");
483    }
484    else
485    {
486       tag_expires = lookup(parameters, "expires");
487       if (*tag_expires == '0')
488       {
489          time_to_live = 0;
490       }
491       else
492       {
493          time_to_live = csp->config->client_tag_lifetime;
494       }
495       toggle_state = lookup(parameters, "toggle-state");
496       if (*toggle_state == '1')
497       {
498          enable_client_specific_tag(csp, toggled_tag, time_to_live);
499       }
500       else
501       {
502          disable_client_specific_tag(csp, toggled_tag);
503       }
504    }
505    rsp->status = strdup_or_die("302 Done dealing with toggle request");
506    if (enlist_unique_header(rsp->headers,
507          "Location", CGI_PREFIX "client-tags"))
508    {
509          return JB_ERR_MEMORY;
510    }
511    return JB_ERR_OK;
512
513 }
514 #endif /* def FEATURE_CLIENT_TAGS */
515
516
517 /*********************************************************************
518  *
519  * Function    :  cgi_send_banner
520  *
521  * Description :  CGI function that returns a banner.
522  *
523  * Parameters  :
524  *          1  :  csp = Current client state (buffers, headers, etc...)
525  *          2  :  rsp = http_response data structure for output
526  *          3  :  parameters = map of cgi parameters
527  *
528  * CGI Parameters :
529  *           type : Selects the type of banner between "trans", "pattern",
530  *                  and "auto". Defaults to "pattern" if absent or invalid.
531  *                  "auto" means to select as if we were image-blocking.
532  *                  (Only the first character really counts; b and t are
533  *                  equivalent).
534  *
535  * Returns     :  JB_ERR_OK on success
536  *                JB_ERR_MEMORY on out-of-memory error.
537  *
538  *********************************************************************/
539 jb_err cgi_send_banner(struct client_state *csp,
540                        struct http_response *rsp,
541                        const struct map *parameters)
542 {
543    char imagetype = lookup(parameters, "type")[0];
544
545    if (imagetype != 'a' && imagetype != 'b' &&
546        imagetype != 'p' && imagetype != 't')
547    {
548       log_error(LOG_LEVEL_ERROR, "Overruling invalid image type '%c'.",
549          imagetype);
550       imagetype = 'p';
551    }
552
553    /*
554     * If type is auto, then determine the right thing
555     * to do from the set-image-blocker action
556     */
557    if (imagetype == 'a')
558    {
559       /*
560        * Default to pattern
561        */
562       imagetype = 'p';
563
564 #ifdef FEATURE_IMAGE_BLOCKING
565       if ((csp->action->flags & ACTION_IMAGE_BLOCKER) != 0)
566       {
567          static const char prefix1[] = CGI_PREFIX "send-banner?type=";
568          static const char prefix2[] = "http://" CGI_SITE_1_HOST "/send-banner?type=";
569          const char *p = csp->action->string[ACTION_STRING_IMAGE_BLOCKER];
570
571          if (p == NULL)
572          {
573             /* Use default - nothing to do here. */
574          }
575          else if (0 == strcmpic(p, "blank"))
576          {
577             imagetype = 'b';
578          }
579          else if (0 == strcmpic(p, "pattern"))
580          {
581             imagetype = 'p';
582          }
583
584          /*
585           * If the action is to call this CGI, determine
586           * the argument:
587           */
588          else if (0 == strncmpic(p, prefix1, sizeof(prefix1) - 1))
589          {
590             imagetype = p[sizeof(prefix1) - 1];
591          }
592          else if (0 == strncmpic(p, prefix2, sizeof(prefix2) - 1))
593          {
594             imagetype = p[sizeof(prefix2) - 1];
595          }
596
597          /*
598           * Everything else must (should) be a URL to
599           * redirect to.
600           */
601          else
602          {
603             imagetype = 'r';
604          }
605       }
606 #endif /* def FEATURE_IMAGE_BLOCKING */
607    }
608
609    /*
610     * Now imagetype is either the non-auto type we were called with,
611     * or it was auto and has since been determined. In any case, we
612     * can proceed to actually answering the request by sending a redirect
613     * or an image as appropriate:
614     */
615    if (imagetype == 'r')
616    {
617       rsp->status = strdup_or_die("302 Local Redirect from Privoxy");
618       if (enlist_unique_header(rsp->headers, "Location",
619                                csp->action->string[ACTION_STRING_IMAGE_BLOCKER]))
620       {
621          return JB_ERR_MEMORY;
622       }
623    }
624    else
625    {
626       if ((imagetype == 'b') || (imagetype == 't'))
627       {
628          rsp->body = bindup(image_blank_data, image_blank_length);
629          rsp->content_length = image_blank_length;
630       }
631       else
632       {
633          rsp->body = bindup(image_pattern_data, image_pattern_length);
634          rsp->content_length = image_pattern_length;
635       }
636
637       if (rsp->body == NULL)
638       {
639          return JB_ERR_MEMORY;
640       }
641       if (enlist(rsp->headers, "Content-Type: " BUILTIN_IMAGE_MIMETYPE))
642       {
643          return JB_ERR_MEMORY;
644       }
645
646       rsp->is_static = 1;
647    }
648
649    return JB_ERR_OK;
650
651 }
652
653
654 /*********************************************************************
655  *
656  * Function    :  cgi_transparent_image
657  *
658  * Description :  CGI function that sends a 1x1 transparent image.
659  *
660  * Parameters  :
661  *          1  :  csp = Current client state (buffers, headers, etc...)
662  *          2  :  rsp = http_response data structure for output
663  *          3  :  parameters = map of cgi parameters
664  *
665  * CGI Parameters : None
666  *
667  * Returns     :  JB_ERR_OK on success
668  *                JB_ERR_MEMORY on out-of-memory error.
669  *
670  *********************************************************************/
671 jb_err cgi_transparent_image(struct client_state *csp,
672                              struct http_response *rsp,
673                              const struct map *parameters)
674 {
675    (void)csp;
676    (void)parameters;
677
678    rsp->body = bindup(image_blank_data, image_blank_length);
679    rsp->content_length = image_blank_length;
680
681    if (rsp->body == NULL)
682    {
683       return JB_ERR_MEMORY;
684    }
685
686    if (enlist(rsp->headers, "Content-Type: " BUILTIN_IMAGE_MIMETYPE))
687    {
688       return JB_ERR_MEMORY;
689    }
690
691    rsp->is_static = 1;
692
693    return JB_ERR_OK;
694
695 }
696
697
698 /*********************************************************************
699  *
700  * Function    :  cgi_send_default_favicon
701  *
702  * Description :  CGI function that sends the standard favicon.
703  *
704  * Parameters  :
705  *          1  :  csp = Current client state (buffers, headers, etc...)
706  *          2  :  rsp = http_response data structure for output
707  *          3  :  parameters = map of cgi parameters
708  *
709  * CGI Parameters : None
710  *
711  * Returns     :  JB_ERR_OK on success
712  *                JB_ERR_MEMORY on out-of-memory error.
713  *
714  *********************************************************************/
715 jb_err cgi_send_default_favicon(struct client_state *csp,
716                                 struct http_response *rsp,
717                                 const struct map *parameters)
718 {
719    static const char default_favicon_data[] =
720       "\000\000\001\000\001\000\020\020\002\000\000\000\000\000\260"
721       "\000\000\000\026\000\000\000\050\000\000\000\020\000\000\000"
722       "\040\000\000\000\001\000\001\000\000\000\000\000\100\000\000"
723       "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000"
724       "\000\000\377\377\377\000\377\000\052\000\017\360\000\000\077"
725       "\374\000\000\161\376\000\000\161\376\000\000\361\377\000\000"
726       "\361\377\000\000\360\017\000\000\360\007\000\000\361\307\000"
727       "\000\361\307\000\000\361\307\000\000\360\007\000\000\160\036"
728       "\000\000\177\376\000\000\077\374\000\000\017\360\000\000\360"
729       "\017\000\000\300\003\000\000\200\001\000\000\200\001\000\000"
730       "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
731       "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
732       "\000\000\200\001\000\000\200\001\000\000\300\003\000\000\360"
733       "\017\000\000";
734    static const size_t favicon_length = sizeof(default_favicon_data) - 1;
735
736    (void)csp;
737    (void)parameters;
738
739    rsp->body = bindup(default_favicon_data, favicon_length);
740    rsp->content_length = favicon_length;
741
742    if (rsp->body == NULL)
743    {
744       return JB_ERR_MEMORY;
745    }
746
747    if (enlist(rsp->headers, "Content-Type: image/x-icon"))
748    {
749       return JB_ERR_MEMORY;
750    }
751
752    rsp->is_static = 1;
753
754    return JB_ERR_OK;
755
756 }
757
758
759 /*********************************************************************
760  *
761  * Function    :  cgi_send_error_favicon
762  *
763  * Description :  CGI function that sends the favicon for error pages.
764  *
765  * Parameters  :
766  *          1  :  csp = Current client state (buffers, headers, etc...)
767  *          2  :  rsp = http_response data structure for output
768  *          3  :  parameters = map of cgi parameters
769  *
770  * CGI Parameters : None
771  *
772  * Returns     :  JB_ERR_OK on success
773  *                JB_ERR_MEMORY on out-of-memory error.
774  *
775  *********************************************************************/
776 jb_err cgi_send_error_favicon(struct client_state *csp,
777                               struct http_response *rsp,
778                               const struct map *parameters)
779 {
780    static const char error_favicon_data[] =
781       "\000\000\001\000\001\000\020\020\002\000\000\000\000\000\260"
782       "\000\000\000\026\000\000\000\050\000\000\000\020\000\000\000"
783       "\040\000\000\000\001\000\001\000\000\000\000\000\100\000\000"
784       "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000"
785       "\000\000\377\377\377\000\000\000\377\000\017\360\000\000\077"
786       "\374\000\000\161\376\000\000\161\376\000\000\361\377\000\000"
787       "\361\377\000\000\360\017\000\000\360\007\000\000\361\307\000"
788       "\000\361\307\000\000\361\307\000\000\360\007\000\000\160\036"
789       "\000\000\177\376\000\000\077\374\000\000\017\360\000\000\360"
790       "\017\000\000\300\003\000\000\200\001\000\000\200\001\000\000"
791       "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
792       "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
793       "\000\000\200\001\000\000\200\001\000\000\300\003\000\000\360"
794       "\017\000\000";
795    static const size_t favicon_length = sizeof(error_favicon_data) - 1;
796
797    (void)csp;
798    (void)parameters;
799
800    rsp->body = bindup(error_favicon_data, favicon_length);
801    rsp->content_length = favicon_length;
802
803    if (rsp->body == NULL)
804    {
805       return JB_ERR_MEMORY;
806    }
807
808    if (enlist(rsp->headers, "Content-Type: image/x-icon"))
809    {
810       return JB_ERR_MEMORY;
811    }
812
813    rsp->is_static = 1;
814
815    return JB_ERR_OK;
816
817 }
818
819
820 /*********************************************************************
821  *
822  * Function    :  cgi_send_stylesheet
823  *
824  * Description :  CGI function that sends a css stylesheet found
825  *                in the cgi-style.css template
826  *
827  * Parameters  :
828  *          1  :  csp = Current client state (buffers, headers, etc...)
829  *          2  :  rsp = http_response data structure for output
830  *          3  :  parameters = map of cgi parameters
831  *
832  * CGI Parameters : None
833  *
834  * Returns     :  JB_ERR_OK on success
835  *                JB_ERR_MEMORY on out-of-memory error.
836  *
837  *********************************************************************/
838 jb_err cgi_send_stylesheet(struct client_state *csp,
839                            struct http_response *rsp,
840                            const struct map *parameters)
841 {
842    jb_err err;
843
844    assert(csp);
845    assert(rsp);
846
847    (void)parameters;
848
849    err = template_load(csp, &rsp->body, "cgi-style.css", 0);
850
851    if (err == JB_ERR_FILE)
852    {
853       /*
854        * No way to tell user; send empty stylesheet
855        */
856       log_error(LOG_LEVEL_ERROR, "Could not find cgi-style.css template");
857    }
858    else if (err)
859    {
860       return err; /* JB_ERR_MEMORY */
861    }
862
863    if (enlist(rsp->headers, "Content-Type: text/css"))
864    {
865       return JB_ERR_MEMORY;
866    }
867
868    return JB_ERR_OK;
869
870 }
871
872
873 /*********************************************************************
874  *
875  * Function    :  cgi_send_wpad
876  *
877  * Description :  CGI function that sends a Proxy Auto-Configuration
878  *                (PAC) file.
879  *
880  * Parameters  :
881  *          1  :  csp = Current client state (buffers, headers, etc...)
882  *          2  :  rsp = http_response data structure for output
883  *          3  :  parameters = map of cgi parameters
884  *
885  * CGI Parameters : None
886  *
887  * Returns     :  JB_ERR_OK on success
888  *                JB_ERR_MEMORY on out-of-memory error.
889  *
890  *********************************************************************/
891 jb_err cgi_send_wpad(struct client_state *csp,
892                      struct http_response *rsp,
893                      const struct map *parameters)
894 {
895    struct map *exports;
896
897    assert(csp);
898    assert(rsp);
899    assert(parameters);
900
901    if (NULL == (exports = default_exports(csp, NULL)))
902    {
903       return JB_ERR_MEMORY;
904    }
905
906    if (enlist(rsp->headers, "Content-Type: application/x-ns-proxy-autoconfig"))
907    {
908       free_map(exports);
909       return JB_ERR_MEMORY;
910    }
911
912    return template_fill_for_cgi(csp, "wpad.dat", exports, rsp);
913
914 }
915
916
917 /*********************************************************************
918  *
919  * Function    :  cgi_send_url_info_osd
920  *
921  * Description :  CGI function that sends the OpenSearch Description
922  *                template for the show-url-info page. It allows to
923  *                access the page through "search engine plugins".
924  *
925  * Parameters  :
926  *          1  :  csp = Current client state (buffers, headers, etc...)
927  *          2  :  rsp = http_response data structure for output
928  *          3  :  parameters = map of cgi parameters
929  *
930  * CGI Parameters : None
931  *
932  * Returns     :  JB_ERR_OK on success
933  *                JB_ERR_MEMORY on out-of-memory error.
934  *
935  *********************************************************************/
936 jb_err cgi_send_url_info_osd(struct client_state *csp,
937                                struct http_response *rsp,
938                                const struct map *parameters)
939 {
940    jb_err err = JB_ERR_MEMORY;
941    struct map *exports = default_exports(csp, NULL);
942
943    (void)csp;
944    (void)parameters;
945
946    if (NULL != exports)
947    {
948       err = template_fill_for_cgi(csp, "url-info-osd.xml", exports, rsp);
949       if (JB_ERR_OK == err)
950       {
951          err = enlist(rsp->headers,
952             "Content-Type: application/opensearchdescription+xml");
953       }
954    }
955
956    return err;
957
958 }
959
960
961 /*********************************************************************
962  *
963  * Function    :  get_content_type
964  *
965  * Description :  Use the file extension to guess the content type
966  *                header we should use to serve the file.
967  *
968  * Parameters  :
969  *          1  :  filename = Name of the file whose content type
970  *                           we care about
971  *
972  * Returns     :  The guessed content type.
973  *
974  *********************************************************************/
975 static const char *get_content_type(const char *filename)
976 {
977    int i;
978    struct content_type
979    {
980       const char extension[6];
981       const char content_type[11];
982    };
983    static const struct content_type content_types[] =
984    {
985       {".css",  "text/css"},
986       {".jpg",  "image/jpeg"},
987       {".jpeg", "image/jpeg"},
988       {".png",  "image/png"},
989    };
990
991    for (i = 0; i < SZ(content_types); i++)
992    {
993       if (strstr(filename, content_types[i].extension))
994       {
995          return content_types[i].content_type;
996       }
997    }
998
999    /* No match by extension, default to html */
1000    return "text/html";
1001 }
1002
1003 /*********************************************************************
1004  *
1005  * Function    :  cgi_send_user_manual
1006  *
1007  * Description :  CGI function that sends a file in the user
1008  *                manual directory.
1009  *
1010  * Parameters  :
1011  *          1  :  csp = Current client state (buffers, headers, etc...)
1012  *          2  :  rsp = http_response data structure for output
1013  *          3  :  parameters = map of cgi parameters
1014  *
1015  * CGI Parameters : file=name.html, the name of the HTML file
1016  *                  (relative to user-manual from config)
1017  *
1018  * Returns     :  JB_ERR_OK on success
1019  *                JB_ERR_MEMORY on out-of-memory error.
1020  *
1021  *********************************************************************/
1022 jb_err cgi_send_user_manual(struct client_state *csp,
1023                             struct http_response *rsp,
1024                             const struct map *parameters)
1025 {
1026    const char *filename;
1027    char *full_path;
1028    jb_err err = JB_ERR_OK;
1029    const char *content_type;
1030
1031    assert(csp);
1032    assert(rsp);
1033    assert(parameters);
1034
1035    if (0 == strncmpic(csp->config->usermanual, "http://", 7) ||
1036        0 == strncmpic(csp->config->usermanual, "https://", 8))
1037    {
1038       log_error(LOG_LEVEL_CGI, "Request for local user-manual "
1039          "received while user-manual delivery is disabled.");
1040       return cgi_error_404(csp, rsp, parameters);
1041    }
1042
1043    if (!parameters->first)
1044    {
1045       /* requested http://p.p/user-manual (without trailing slash) */
1046       return cgi_redirect(rsp, CGI_PREFIX "user-manual/");
1047    }
1048
1049    get_string_param(parameters, "file", &filename);
1050    if (filename == NULL)
1051    {
1052       /* It's '/' so serve the index.html if there is one.  */
1053       filename = "index.html";
1054    }
1055    else if (NULL != strchr(filename, '/') || NULL != strstr(filename, ".."))
1056    {
1057       /*
1058        * We currently only support a flat file
1059        * hierarchy for the documentation.
1060        */
1061       log_error(LOG_LEVEL_ERROR,
1062          "Rejecting the request to serve '%s' as it contains '/' or '..'",
1063          filename);
1064       return JB_ERR_CGI_PARAMS;
1065    }
1066
1067    full_path = make_path(csp->config->usermanual, filename);
1068    if (full_path == NULL)
1069    {
1070       return JB_ERR_MEMORY;
1071    }
1072
1073    err = load_file(full_path, &rsp->body, &rsp->content_length);
1074    if (JB_ERR_OK != err)
1075    {
1076       assert((JB_ERR_FILE == err) || (JB_ERR_MEMORY == err));
1077       if (JB_ERR_FILE == err)
1078       {
1079          err = cgi_error_no_template(csp, rsp, full_path);
1080       }
1081       freez(full_path);
1082       return err;
1083    }
1084    freez(full_path);
1085
1086    content_type = get_content_type(filename);
1087    log_error(LOG_LEVEL_CGI,
1088       "Content-Type guessed for %s: %s", filename, content_type);
1089
1090    return enlist_unique_header(rsp->headers, "Content-Type", content_type);
1091
1092 }
1093
1094
1095 #ifdef FEATURE_EXTENDED_STATISTICS
1096 /*********************************************************************
1097  *
1098  * Function    :  get_block_reason_statistics_table
1099  *
1100  * Description :  Produces the block reason statistic table content.
1101  *
1102  * Parameters  :
1103  *          1  :  csp = Current client state (buffers, headers, etc...)
1104  *
1105  * Returns     :  Pointer to the HTML statistic table content or
1106  *                NULL on out of memory
1107  *
1108  *********************************************************************/
1109 static char *get_block_reason_statistics_table(const struct client_state *csp)
1110 {
1111    char buf[BUFFER_SIZE];
1112    char *statistics;
1113    int i;
1114    struct file_list *fl;
1115    jb_err err = JB_ERR_OK;
1116
1117    statistics = strdup_or_die("");
1118
1119    /* Run through all action files. */
1120    for (i = 0; i < MAX_AF_FILES; i++)
1121    {
1122       struct url_actions *b;
1123       struct action_spec *last_action = NULL;
1124
1125       if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
1126       {
1127          /* Skip empty files */
1128          continue;
1129       }
1130
1131       /* Go through all the actions. */
1132       for (b = b->next; NULL != b; b = b->next)
1133       {
1134          if (last_action == b->action)
1135          {
1136             continue;
1137          }
1138          if ((b->action->add & ACTION_BLOCK))
1139          {
1140             unsigned long long count;
1141             const char *block_reason = b->action->string[ACTION_STRING_BLOCK];
1142             const char *encoded_block_reason = html_encode(block_reason);
1143
1144             if (encoded_block_reason == NULL)
1145             {
1146                freez(statistics);
1147                return NULL;
1148             }
1149             get_block_reason_count(block_reason, &count);
1150             snprintf(buf, sizeof(buf),
1151                "<tr><td>%s</td><td style=\"text-align: right\">%llu</td>\n",
1152                encoded_block_reason, count);
1153             freez(encoded_block_reason);
1154
1155             if (!err) err = string_append(&statistics, buf);
1156          }
1157          last_action = b->action;
1158       }
1159    }
1160
1161    return statistics;
1162
1163 }
1164
1165
1166 /*********************************************************************
1167  *
1168  * Function    :  get_filter_statistics_table
1169  *
1170  * Description :  Produces the filter statistic table content.
1171  *
1172  * Parameters  :
1173  *          1  :  csp = Current client state (buffers, headers, etc...)
1174  *
1175  * Returns     :  Pointer to the HTML statistic table content or
1176  *                NULL on out of memory
1177  *
1178  *********************************************************************/
1179 static char *get_filter_statistics_table(const struct client_state *csp)
1180 {
1181    char buf[BUFFER_SIZE];
1182    char *statistics;
1183    int i;
1184    struct file_list *fl;
1185    struct re_filterfile_spec *b;
1186    jb_err err = JB_ERR_OK;
1187
1188    statistics = strdup_or_die("");
1189
1190    for (i = 0; i < MAX_AF_FILES; i++)
1191    {
1192      fl = csp->rlist[i];
1193      if ((NULL == fl) || (NULL == fl->f))
1194      {
1195         /*
1196          * Either there are no filter files left or this
1197          * filter file just contains no valid filters.
1198          *
1199          * Continue to be sure we don't miss valid filter
1200          * files that are chained after empty or invalid ones.
1201          */
1202         continue;
1203      }
1204
1205      for (b = fl->f; b != NULL; b = b->next)
1206      {
1207         if (b->type == FT_CONTENT_FILTER)
1208         {
1209            unsigned long long executions;
1210            unsigned long long response_bodies_modified;
1211            unsigned long long hits;
1212
1213            get_filter_statistics(b->name, &executions, &response_bodies_modified, &hits);
1214            snprintf(buf, sizeof(buf),
1215               "<tr><td>%s</td><td style=\"text-align: right\">%llu</td>"
1216               "<td style=\"text-align: right\">%llu</td>"
1217               "<td style=\"text-align: right\">%llu</td><tr>\n",
1218               b->name, executions, response_bodies_modified, hits);
1219
1220            if (!err) err = string_append(&statistics, buf);
1221         }
1222      }
1223    }
1224
1225    return statistics;
1226
1227 }
1228 #endif /* def FEATURE_EXTENDED_STATISTICS */
1229
1230
1231 /*********************************************************************
1232  *
1233  * Function    :  cgi_show_status
1234  *
1235  * Description :  CGI function that returns a web page describing the
1236  *                current status of Privoxy.
1237  *
1238  * Parameters  :
1239  *          1  :  csp = Current client state (buffers, headers, etc...)
1240  *          2  :  rsp = http_response data structure for output
1241  *          3  :  parameters = map of cgi parameters
1242  *
1243  * CGI Parameters :
1244  *        file :  Which file to show.  Only first letter is checked,
1245  *                valid values are:
1246  *                - "a"ction file
1247  *                - "r"egex
1248  *                - "t"rust
1249  *                Default is to show menu and other information.
1250  *
1251  * Returns     :  JB_ERR_OK on success
1252  *                JB_ERR_MEMORY on out-of-memory error.
1253  *
1254  *********************************************************************/
1255 jb_err cgi_show_status(struct client_state *csp,
1256                        struct http_response *rsp,
1257                        const struct map *parameters)
1258 {
1259    char *s = NULL;
1260    unsigned i;
1261    int j;
1262
1263    char buf[BUFFER_SIZE];
1264 #ifdef FEATURE_STATISTICS
1265 #ifdef MUTEX_LOCKS_AVAILABLE
1266    float percentage_blocked;
1267    unsigned long long local_number_of_requests_received;
1268    unsigned long long local_number_of_requests_blocked;
1269 #else
1270    float perc_rej;   /* Percentage of http requests rejected */
1271    int local_urls_read;
1272    int local_urls_rejected;
1273 #endif
1274 #endif /* ndef FEATURE_STATISTICS */
1275    jb_err err = JB_ERR_OK;
1276
1277    struct map *exports;
1278
1279    assert(csp);
1280    assert(rsp);
1281    assert(parameters);
1282
1283    if ('\0' != *(lookup(parameters, "file")))
1284    {
1285       return cgi_show_file(csp, rsp, parameters);
1286    }
1287
1288    if (NULL == (exports = default_exports(csp, "show-status")))
1289    {
1290       return JB_ERR_MEMORY;
1291    }
1292
1293    s = strdup("");
1294    for (j = 0; (s != NULL) && (j < Argc); j++)
1295    {
1296       if (!err) err = string_join  (&s, html_encode(Argv[j]));
1297       if (!err) err = string_append(&s, " ");
1298    }
1299    if (!err) err = map(exports, "invocation", 1, s, 0);
1300
1301    if (!err) err = map(exports, "options", 1, csp->config->proxy_args, 1);
1302    if (!err) err = show_defines(exports);
1303
1304    if (err)
1305    {
1306       free_map(exports);
1307       return JB_ERR_MEMORY;
1308    }
1309
1310 #ifdef FEATURE_STATISTICS
1311 #ifdef MUTEX_LOCKS_AVAILABLE
1312    privoxy_mutex_lock(&block_statistics_mutex);
1313    local_number_of_requests_received = number_of_requests_received;
1314    local_number_of_requests_blocked = number_of_requests_blocked;
1315    privoxy_mutex_unlock(&block_statistics_mutex);
1316 #else
1317    local_urls_read     = urls_read;
1318    local_urls_rejected = urls_rejected;
1319 #endif
1320    /*
1321     * Need to alter the stats not to include the fetch of this
1322     * page.
1323     *
1324     * Can't do following thread safely! doh!
1325     *
1326     * urls_read--;
1327     * urls_rejected--; * This will be incremented subsequently *
1328     */
1329
1330 #ifdef MUTEX_LOCKS_AVAILABLE
1331    if (local_number_of_requests_received == 0)
1332 #else
1333    if (local_urls_read == 0)
1334 #endif
1335    {
1336       if (!err) err = map_block_killer(exports, "have-stats");
1337    }
1338    else
1339    {
1340       if (!err) err = map_block_killer(exports, "have-no-stats");
1341
1342 #ifdef MUTEX_LOCKS_AVAILABLE
1343       percentage_blocked = (float)local_number_of_requests_blocked * 100.0F /
1344             (float)local_number_of_requests_received;
1345
1346       snprintf(buf, sizeof(buf), "%llu", local_number_of_requests_received);
1347       if (!err) err = map(exports, "requests-received", 1, buf, 1);
1348
1349       snprintf(buf, sizeof(buf), "%llu", local_number_of_requests_blocked);
1350       if (!err) err = map(exports, "requests-blocked", 1, buf, 1);
1351
1352       snprintf(buf, sizeof(buf), "%6.2f", percentage_blocked);
1353       if (!err) err = map(exports, "percent-blocked", 1, buf, 1);
1354 #else
1355       perc_rej = (float)local_urls_rejected * 100.0F /
1356             (float)local_urls_read;
1357
1358       snprintf(buf, sizeof(buf), "%d", local_urls_read);
1359       if (!err) err = map(exports, "requests-received", 1, buf, 1);
1360
1361       snprintf(buf, sizeof(buf), "%d", local_urls_rejected);
1362       if (!err) err = map(exports, "requests-blocked", 1, buf, 1);
1363
1364       snprintf(buf, sizeof(buf), "%6.2f", perc_rej);
1365       if (!err) err = map(exports, "percent-blocked", 1, buf, 1);
1366 #endif
1367    }
1368
1369 #else /* ndef FEATURE_STATISTICS */
1370    if (!err) err = map_block_killer(exports, "statistics");
1371 #endif /* ndef FEATURE_STATISTICS */
1372
1373 #ifdef FEATURE_EXTENDED_STATISTICS
1374    if (!err)
1375    {
1376       char *block_reason_statistics = get_block_reason_statistics_table(csp);
1377       if (block_reason_statistics != NULL)
1378       {
1379          err = map(exports, "block-reason-statistics", 1, block_reason_statistics, 0);
1380       }
1381       else
1382       {
1383          err = map_block_killer(exports, "extended-statistics");
1384       }
1385    }
1386    if (!err)
1387    {
1388       char *filter_statistics = get_filter_statistics_table(csp);
1389       if (filter_statistics != NULL)
1390       {
1391          err = map(exports, "filter-statistics", 1, filter_statistics, 0);
1392       }
1393       else
1394       {
1395          err = map_block_killer(exports, "extended-statistics");
1396       }
1397    }
1398 #else /* ndef FEATURE_EXTENDED_STATISTICS */
1399    if (!err) err = map_block_killer(exports, "extended-statistics");
1400 #endif /* def FEATURE_EXTENDED_STATISTICS */
1401
1402    /*
1403     * List all action files in use, together with view and edit links,
1404     * except for standard.action, which should only be viewable. (Not
1405     * enforced in the editor itself)
1406     * FIXME: Shouldn't include hardwired HTML here, use line template instead!
1407     */
1408    s = strdup("");
1409    for (i = 0; i < MAX_AF_FILES; i++)
1410    {
1411       if (csp->actions_list[i] != NULL)
1412       {
1413          if (!err) err = string_append(&s, "<tr><td>");
1414          if (!err) err = string_join(&s, html_encode(csp->actions_list[i]->filename));
1415          snprintf(buf, sizeof(buf),
1416             "</td><td class=\"buttons\"><a href=\"/show-status?file=actions&amp;index=%u\">View</a>", i);
1417          if (!err) err = string_append(&s, buf);
1418
1419 #ifdef FEATURE_CGI_EDIT_ACTIONS
1420          if ((csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS)
1421             && (NULL != csp->config->actions_file_short[i]))
1422          {
1423 #ifdef HAVE_ACCESS
1424             if (access(csp->config->actions_file[i], W_OK) == 0)
1425             {
1426 #endif /* def HAVE_ACCESS */
1427                snprintf(buf, sizeof(buf), "&nbsp;&nbsp;<a href=\"/edit-actions-list?f=%u\">Edit</a>", i);
1428                if (!err) err = string_append(&s, buf);
1429 #ifdef HAVE_ACCESS
1430             }
1431             else
1432             {
1433                if (!err) err = string_append(&s, "&nbsp;&nbsp;<strong>No write access.</strong>");
1434             }
1435 #endif /* def HAVE_ACCESS */
1436          }
1437 #endif
1438
1439          if (!err) err = string_append(&s, "</td></tr>\n");
1440       }
1441    }
1442    if (!err && *s != '\0')
1443    {
1444       err = map(exports, "actions-filenames", 1, s, 0);
1445    }
1446    else
1447    {
1448       if (!err) err = map(exports, "actions-filenames", 1, "<tr><td>None specified</td></tr>", 1);
1449       freez(s);
1450    }
1451
1452    /*
1453     * List all re_filterfiles in use, together with view options.
1454     * FIXME: Shouldn't include hardwired HTML here, use line template instead!
1455     */
1456    s = strdup("");
1457    for (i = 0; i < MAX_AF_FILES; i++)
1458    {
1459       if (csp->rlist[i] != NULL)
1460       {
1461          if (!err) err = string_append(&s, "<tr><td>");
1462          if (!err) err = string_join(&s, html_encode(csp->rlist[i]->filename));
1463          snprintf(buf, sizeof(buf),
1464             "</td><td class=\"buttons\"><a href=\"/show-status?file=filter&amp;index=%u\">View</a>", i);
1465          if (!err) err = string_append(&s, buf);
1466          if (!err) err = string_append(&s, "</td></tr>\n");
1467       }
1468    }
1469    if (!err && *s != '\0')
1470    {
1471       err = map(exports, "re-filter-filenames", 1, s, 0);
1472    }
1473    else
1474    {
1475       if (!err) err = map(exports, "re-filter-filenames", 1, "<tr><td>None specified</td></tr>", 1);
1476       if (!err) err = map_block_killer(exports, "have-filterfile");
1477       freez(s);
1478    }
1479
1480 #ifdef FEATURE_TRUST
1481    if (csp->tlist)
1482    {
1483       if (!err) err = map(exports, "trust-filename", 1, html_encode(csp->tlist->filename), 0);
1484    }
1485    else
1486    {
1487       if (!err) err = map(exports, "trust-filename", 1, "None specified", 1);
1488       if (!err) err = map_block_killer(exports, "have-trustfile");
1489    }
1490 #else
1491    if (!err) err = map_block_killer(exports, "trust-support");
1492 #endif /* ndef FEATURE_TRUST */
1493
1494 #ifdef FEATURE_CGI_EDIT_ACTIONS
1495    if (!err && (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
1496    {
1497       err = map_block_killer(exports, "cgi-editor-is-disabled");
1498    }
1499 #endif /* ndef CGI_EDIT_ACTIONS */
1500
1501    if (!err) err = map(exports, "force-prefix", 1, FORCE_PREFIX, 1);
1502
1503    if (err)
1504    {
1505       free_map(exports);
1506       return JB_ERR_MEMORY;
1507    }
1508
1509    return template_fill_for_cgi(csp, "show-status", exports, rsp);
1510 }
1511
1512
1513 /*********************************************************************
1514  *
1515  * Function    :  cgi_show_url_info
1516  *
1517  * Description :  CGI function that determines and shows which actions
1518  *                Privoxy will perform for a given url, and which
1519  *                matches starting from the defaults have lead to that.
1520  *
1521  * Parameters  :
1522  *          1  :  csp = Current client state (buffers, headers, etc...)
1523  *          2  :  rsp = http_response data structure for output
1524  *          3  :  parameters = map of cgi parameters
1525  *
1526  * CGI Parameters :
1527  *            url : The url whose actions are to be determined.
1528  *                  If url is unset, the url-given conditional will be
1529  *                  set, so that all but the form can be suppressed in
1530  *                  the template.
1531  *
1532  * Returns     :  JB_ERR_OK on success
1533  *                JB_ERR_MEMORY on out-of-memory error.
1534  *
1535  *********************************************************************/
1536 jb_err cgi_show_url_info(struct client_state *csp,
1537                          struct http_response *rsp,
1538                          const struct map *parameters)
1539 {
1540    char *url_param;
1541    struct map *exports;
1542    char buf[150];
1543
1544    assert(csp);
1545    assert(rsp);
1546    assert(parameters);
1547
1548    if (NULL == (exports = default_exports(csp, "show-url-info")))
1549    {
1550       return JB_ERR_MEMORY;
1551    }
1552
1553    /*
1554     * Get the url= parameter (if present) and remove any leading/trailing spaces.
1555     */
1556    url_param = strdup_or_die(lookup(parameters, "url"));
1557    chomp(url_param);
1558
1559    /*
1560     * Handle prefixes.  4 possibilities:
1561     * 1) "http://" or "https://" prefix present and followed by URL - OK
1562     * 2) Only the "http://" or "https://" part is present, no URL - change
1563     *    to empty string so it will be detected later as "no URL".
1564     * 3) Parameter specified but doesn't start with "http(s?)://" - add a
1565     *    "http://" prefix.
1566     * 4) Parameter not specified or is empty string - let this fall through
1567     *    for now, next block of code will handle it.
1568     */
1569    if (0 == strncmp(url_param, "http://", 7))
1570    {
1571       if (url_param[7] == '\0')
1572       {
1573          /*
1574           * Empty URL (just prefix).
1575           * Make it totally empty so it's caught by the next if ()
1576           */
1577          url_param[0] = '\0';
1578       }
1579    }
1580    else if (0 == strncmp(url_param, "https://", 8))
1581    {
1582       if (url_param[8] == '\0')
1583       {
1584          /*
1585           * Empty URL (just prefix).
1586           * Make it totally empty so it's caught by the next if ()
1587           */
1588          url_param[0] = '\0';
1589       }
1590    }
1591    else if ((url_param[0] != '\0')
1592       && ((NULL == strstr(url_param, "://")
1593             || (strstr(url_param, "://") > strstr(url_param, "/")))))
1594    {
1595       /*
1596        * No prefix or at least no prefix before
1597        * the first slash - assume http://
1598        */
1599       char *url_param_prefixed = strdup_or_die("http://");
1600
1601       if (JB_ERR_OK != string_join(&url_param_prefixed, url_param))
1602       {
1603          free_map(exports);
1604          return JB_ERR_MEMORY;
1605       }
1606       url_param = url_param_prefixed;
1607    }
1608
1609    /*
1610     * Hide "toggle off" warning if Privoxy is toggled on.
1611     */
1612    if (
1613 #ifdef FEATURE_TOGGLE
1614        (global_toggle_state == 1) &&
1615 #endif /* def FEATURE_TOGGLE */
1616        map_block_killer(exports, "privoxy-is-toggled-off")
1617       )
1618    {
1619       freez(url_param);
1620       free_map(exports);
1621       return JB_ERR_MEMORY;
1622    }
1623
1624    if (url_param[0] == '\0')
1625    {
1626       /* URL parameter not specified, display query form only. */
1627       free(url_param);
1628       if (map_block_killer(exports, "url-given")
1629         || map(exports, "url", 1, "", 1))
1630       {
1631          free_map(exports);
1632          return JB_ERR_MEMORY;
1633       }
1634    }
1635    else
1636    {
1637       /* Given a URL, so query it. */
1638       jb_err err;
1639       char *matches;
1640       char *s;
1641       int hits = 0;
1642       struct file_list *fl;
1643       struct url_actions *b;
1644       struct http_request url_to_query[1];
1645       struct current_action_spec action[1];
1646       int i;
1647
1648       if (map(exports, "url", 1, html_encode(url_param), 0))
1649       {
1650          free(url_param);
1651          free_map(exports);
1652          return JB_ERR_MEMORY;
1653       }
1654
1655       init_current_action(action);
1656
1657       if (map(exports, "default", 1, current_action_to_html(csp, action), 0))
1658       {
1659          free_current_action(action);
1660          free(url_param);
1661          free_map(exports);
1662          return JB_ERR_MEMORY;
1663       }
1664
1665       memset(url_to_query, '\0', sizeof(url_to_query));
1666       err = parse_http_url(url_param, url_to_query, REQUIRE_PROTOCOL);
1667       assert((err != JB_ERR_OK) || (url_to_query->ssl == !strncmpic(url_param, "https://", 8)));
1668
1669       free(url_param);
1670
1671       if (err == JB_ERR_MEMORY)
1672       {
1673          free_http_request(url_to_query);
1674          free_current_action(action);
1675          free_map(exports);
1676          return JB_ERR_MEMORY;
1677       }
1678       else if (err)
1679       {
1680          /* Invalid URL */
1681
1682          err = map(exports, "matches", 1, "<b>[Invalid URL specified!]</b>" , 1);
1683          if (!err) err = map(exports, "final", 1, lookup(exports, "default"), 1);
1684          if (!err) err = map_block_killer(exports, "valid-url");
1685
1686          free_current_action(action);
1687          free_http_request(url_to_query);
1688
1689          if (err)
1690          {
1691             free_map(exports);
1692             return JB_ERR_MEMORY;
1693          }
1694
1695          return template_fill_for_cgi(csp, "show-url-info", exports, rsp);
1696       }
1697
1698       /*
1699        * We have a warning about SSL paths. Hide it for unencrypted sites
1700        * and unconditionally if https inspection is enabled.
1701        */
1702 #ifndef FEATURE_HTTPS_INSPECTION
1703       if (!url_to_query->ssl)
1704 #endif
1705       {
1706          if (map_block_killer(exports, "https-and-no-https-inspection"))
1707          {
1708             free_current_action(action);
1709             free_map(exports);
1710             free_http_request(url_to_query);
1711             return JB_ERR_MEMORY;
1712          }
1713       }
1714
1715       matches = strdup_or_die("<table summary=\"\" class=\"transparent\">");
1716
1717       for (i = 0; i < MAX_AF_FILES; i++)
1718       {
1719          if (NULL == csp->config->actions_file_short[i]
1720              || !strcmp(csp->config->actions_file_short[i], "standard.action")) continue;
1721
1722          b = NULL;
1723          hits = 1;
1724          if ((fl = csp->actions_list[i]) != NULL)
1725          {
1726             if ((b = fl->f) != NULL)
1727             {
1728                /* FIXME: Hardcoded HTML! */
1729                string_append(&matches, "<tr><th>In file: ");
1730                string_join  (&matches, html_encode(csp->config->actions_file_short[i]));
1731                snprintf(buf, sizeof(buf), " <a class=\"cmd\" href=\"/show-status?file=actions&amp;index=%d\">", i);
1732                string_append(&matches, buf);
1733                string_append(&matches, "View</a>");
1734 #ifdef FEATURE_CGI_EDIT_ACTIONS
1735                if (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS)
1736                {
1737 #ifdef HAVE_ACCESS
1738                   if (access(csp->config->actions_file[i], W_OK) == 0)
1739                   {
1740 #endif /* def HAVE_ACCESS */
1741                      snprintf(buf, sizeof(buf),
1742                         " <a class=\"cmd\" href=\"/edit-actions-list?f=%d\">", i);
1743                      string_append(&matches, buf);
1744                      string_append(&matches, "Edit</a>");
1745 #ifdef HAVE_ACCESS
1746                   }
1747                   else
1748                   {
1749                      string_append(&matches, " <strong>No write access.</strong>");
1750                   }
1751 #endif /* def HAVE_ACCESS */
1752                }
1753 #endif /* FEATURE_CGI_EDIT_ACTIONS */
1754
1755                string_append(&matches, "</th></tr>\n");
1756
1757                hits = 0;
1758                b = b->next;
1759             }
1760          }
1761
1762          for (; (b != NULL) && (matches != NULL); b = b->next)
1763          {
1764             if (url_match(b->url, url_to_query))
1765             {
1766                string_append(&matches, "<tr><td>{");
1767                string_join  (&matches, actions_to_html(csp, b->action));
1768                string_append(&matches, " }<br>\n<code>");
1769                string_join  (&matches, html_encode(b->url->spec));
1770                string_append(&matches, "</code></td></tr>\n");
1771
1772                if (merge_current_action(action, b->action))
1773                {
1774                   freez(matches);
1775                   free_http_request(url_to_query);
1776                   free_current_action(action);
1777                   free_map(exports);
1778                   return JB_ERR_MEMORY;
1779                }
1780                hits++;
1781             }
1782          }
1783
1784          if (!hits)
1785          {
1786             string_append(&matches, "<tr><td>(no matches in this file)</td></tr>\n");
1787          }
1788       }
1789       string_append(&matches, "</table>\n");
1790
1791       /*
1792        * XXX: Kludge to make sure the "Forward settings" section
1793        * shows what forward-override{} would do with the requested URL.
1794        * No one really cares how the CGI request would be forwarded
1795        * if it wasn't intercepted as CGI request in the first place.
1796        *
1797        * From here on the action bitmask will no longer reflect
1798        * the real url (http://config.privoxy.org/show-url-info?url=.*),
1799        * but luckily it's no longer required later on anyway.
1800        */
1801       free_current_action(csp->action);
1802       get_url_actions(csp, url_to_query);
1803
1804       /*
1805        * Fill in forwarding settings.
1806        *
1807        * The possibilities are:
1808        *  - no forwarding
1809        *  - http forwarding only
1810        *  - socks4(a) forwarding only
1811        *  - socks4(a) and http forwarding.
1812        *
1813        * XXX: Parts of this code could be reused for the
1814        * "forwarding-failed" template which currently doesn't
1815        * display the proxy port and an eventual second forwarder.
1816        */
1817       {
1818          const struct forward_spec *fwd = forward_url(csp, url_to_query);
1819
1820          if ((fwd->gateway_host == NULL) && (fwd->forward_host == NULL))
1821          {
1822             if (!err) err = map_block_killer(exports, "socks-forwarder");
1823             if (!err) err = map_block_killer(exports, "http-forwarder");
1824          }
1825          else
1826          {
1827             char port[10]; /* We save proxy ports as int but need a string here */
1828
1829             if (!err) err = map_block_killer(exports, "no-forwarder");
1830
1831             if (fwd->gateway_host != NULL)
1832             {
1833                char *socks_type = NULL;
1834
1835                switch (fwd->type)
1836                {
1837                   case SOCKS_4:
1838                      socks_type = "socks4";
1839                      break;
1840                   case SOCKS_4A:
1841                      socks_type = "socks4a";
1842                      break;
1843                   case SOCKS_5:
1844                      socks_type = "socks5";
1845                      break;
1846                   case SOCKS_5T:
1847                      socks_type = "socks5t";
1848                      break;
1849                   default:
1850                      log_error(LOG_LEVEL_FATAL, "Unknown socks type: %d.", fwd->type);
1851                }
1852
1853                if (!err) err = map(exports, "socks-type", 1, socks_type, 1);
1854                if (!err) err = map(exports, "gateway-host", 1, fwd->gateway_host, 1);
1855                snprintf(port, sizeof(port), "%d", fwd->gateway_port);
1856                if (!err) err = map(exports, "gateway-port", 1, port, 1);
1857             }
1858             else
1859             {
1860                if (!err) err = map_block_killer(exports, "socks-forwarder");
1861             }
1862
1863             if (fwd->forward_host != NULL)
1864             {
1865                if (!err) err = map(exports, "forward-host", 1, fwd->forward_host, 1);
1866                snprintf(port, sizeof(port), "%d", fwd->forward_port);
1867                if (!err) err = map(exports, "forward-port", 1, port, 1);
1868             }
1869             else
1870             {
1871                if (!err) err = map_block_killer(exports, "http-forwarder");
1872             }
1873          }
1874       }
1875
1876       free_http_request(url_to_query);
1877
1878       if (err || matches == NULL)
1879       {
1880          free_current_action(action);
1881          free_map(exports);
1882          return JB_ERR_MEMORY;
1883       }
1884
1885 #ifdef FEATURE_CGI_EDIT_ACTIONS
1886       if ((csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
1887       {
1888          err = map_block_killer(exports, "cgi-editor-is-disabled");
1889       }
1890 #endif /* FEATURE_CGI_EDIT_ACTIONS */
1891
1892       /*
1893        * If zlib support is available, if no content filters
1894        * are enabled or if the prevent-compression action is enabled,
1895        * suppress the "compression could prevent filtering" warning.
1896        */
1897 #ifndef FEATURE_ZLIB
1898       if (!content_filters_enabled(action) ||
1899          (action->flags & ACTION_NO_COMPRESSION))
1900 #endif
1901       {
1902          if (!err) err = map_block_killer(exports, "filters-might-be-ineffective");
1903       }
1904
1905       if (err || map(exports, "matches", 1, matches , 0))
1906       {
1907          free_current_action(action);
1908          free_map(exports);
1909          return JB_ERR_MEMORY;
1910       }
1911
1912       s = current_action_to_html(csp, action);
1913
1914       free_current_action(action);
1915
1916       if (map(exports, "final", 1, s, 0))
1917       {
1918          free_map(exports);
1919          return JB_ERR_MEMORY;
1920       }
1921    }
1922
1923    return template_fill_for_cgi(csp, "show-url-info", exports, rsp);
1924 }
1925
1926
1927 /*********************************************************************
1928  *
1929  * Function    :  cgi_robots_txt
1930  *
1931  * Description :  CGI function to return "/robots.txt".
1932  *
1933  * Parameters  :
1934  *          1  :  csp = Current client state (buffers, headers, etc...)
1935  *          2  :  rsp = http_response data structure for output
1936  *          3  :  parameters = map of cgi parameters
1937  *
1938  * CGI Parameters : None
1939  *
1940  * Returns     :  JB_ERR_OK on success
1941  *                JB_ERR_MEMORY on out-of-memory error.
1942  *
1943  *********************************************************************/
1944 jb_err cgi_robots_txt(struct client_state *csp,
1945                       struct http_response *rsp,
1946                       const struct map *parameters)
1947 {
1948    char buf[100];
1949    jb_err err;
1950
1951    (void)csp;
1952    (void)parameters;
1953
1954    rsp->body = strdup_or_die(
1955       "# This is the Privoxy control interface.\n"
1956       "# It isn't very useful to index it, and you're likely to break stuff.\n"
1957       "# So go away!\n"
1958       "\n"
1959       "User-agent: *\n"
1960       "Disallow: /\n"
1961       "\n");
1962
1963    err = enlist_unique(rsp->headers, "Content-Type: text/plain", 13);
1964
1965    rsp->is_static = 1;
1966
1967    get_http_time(7 * 24 * 60 * 60, buf, sizeof(buf)); /* 7 days into future */
1968    if (!err) err = enlist_unique_header(rsp->headers, "Expires", buf);
1969
1970    return (err ? JB_ERR_MEMORY : JB_ERR_OK);
1971 }
1972
1973
1974 /*********************************************************************
1975  *
1976  * Function    :  show_defines
1977  *
1978  * Description :  Add to a map the state of all conditional #defines
1979  *                used when building
1980  *
1981  * Parameters  :
1982  *          1  :  exports = map to extend
1983  *
1984  * Returns     :  JB_ERR_OK on success
1985  *                JB_ERR_MEMORY on out-of-memory error.
1986  *
1987  *********************************************************************/
1988 static jb_err show_defines(struct map *exports)
1989 {
1990    jb_err err = JB_ERR_OK;
1991    int i;
1992    struct feature {
1993       const char name[31];
1994       const unsigned char is_available;
1995    };
1996
1997    static const struct feature features[] = {
1998       {
1999          "FEATURE_64_BIT_TIME_T",
2000 #if (SIZEOF_TIME_T == 8)
2001          1,
2002 #else
2003          0,
2004 #endif
2005       },
2006       {
2007          "FEATURE_ACCEPT_FILTER",
2008 #ifdef FEATURE_ACCEPT_FILTER
2009          1,
2010 #else
2011          0,
2012 #endif
2013       },
2014       {
2015          "FEATURE_ACL",
2016 #ifdef FEATURE_ACL
2017          1,
2018 #else
2019          0,
2020 #endif
2021       },
2022       {
2023          "FEATURE_BROTLI",
2024 #ifdef FEATURE_BROTLI
2025          1,
2026 #else
2027          0,
2028 #endif
2029       },
2030       {
2031          "FEATURE_CGI_EDIT_ACTIONS",
2032 #ifdef FEATURE_CGI_EDIT_ACTIONS
2033          1,
2034 #else
2035          0,
2036 #endif
2037       },
2038       {
2039          "FEATURE_CLIENT_TAGS",
2040 #ifdef FEATURE_CLIENT_TAGS
2041          1,
2042 #else
2043          0,
2044 #endif
2045       },
2046       {
2047          "FEATURE_COMPRESSION",
2048 #ifdef FEATURE_COMPRESSION
2049          1,
2050 #else
2051          0,
2052 #endif
2053       },
2054       {
2055          "FEATURE_CONNECTION_KEEP_ALIVE",
2056 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2057          1,
2058 #else
2059          0,
2060 #endif
2061       },
2062       {
2063          "FEATURE_CONNECTION_SHARING",
2064 #ifdef FEATURE_CONNECTION_SHARING
2065          1,
2066 #else
2067          0,
2068 #endif
2069       },
2070       {
2071          "FEATURE_EXTERNAL_FILTERS",
2072 #ifdef FEATURE_EXTERNAL_FILTERS
2073          1,
2074 #else
2075          0,
2076 #endif
2077       },
2078       {
2079          "FEATURE_FAST_REDIRECTS",
2080 #ifdef FEATURE_FAST_REDIRECTS
2081          1,
2082 #else
2083          0,
2084 #endif
2085       },
2086       {
2087          "FEATURE_FORCE_LOAD",
2088 #ifdef FEATURE_FORCE_LOAD
2089          1,
2090 #else
2091          0,
2092 #endif
2093       },
2094       {
2095          "FEATURE_GRACEFUL_TERMINATION",
2096 #ifdef FEATURE_GRACEFUL_TERMINATION
2097          1,
2098 #else
2099          0,
2100 #endif
2101       },
2102       {
2103          "FEATURE_HTTPS_INSPECTION",
2104 #ifdef FEATURE_HTTPS_INSPECTION
2105          1,
2106 #else
2107          0,
2108 #endif
2109       },
2110       {
2111          "FEATURE_IMAGE_BLOCKING",
2112 #ifdef FEATURE_IMAGE_BLOCKING
2113          1,
2114 #else
2115          0,
2116 #endif
2117       },
2118       {
2119          "FEATURE_IPV6_SUPPORT",
2120 #ifdef HAVE_RFC2553
2121          1,
2122 #else
2123          0,
2124 #endif
2125       },
2126       {
2127          "FEATURE_NO_GIFS",
2128 #ifdef FEATURE_NO_GIFS
2129          1,
2130 #else
2131          0,
2132 #endif
2133       },
2134       {
2135          "FEATURE_PTHREAD",
2136 #ifdef FEATURE_PTHREAD
2137          1,
2138 #else
2139          0,
2140 #endif
2141       },
2142       {
2143          "FEATURE_STATISTICS",
2144 #ifdef FEATURE_STATISTICS
2145          1,
2146 #else
2147          0,
2148 #endif
2149       },
2150       {
2151          "FEATURE_STRPTIME_SANITY_CHECKS",
2152 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
2153          1,
2154 #else
2155          0,
2156 #endif
2157       },
2158       {
2159          "FEATURE_TOGGLE",
2160 #ifdef FEATURE_TOGGLE
2161          1,
2162 #else
2163          0,
2164 #endif
2165       },
2166       {
2167          "FEATURE_TRUST",
2168 #ifdef FEATURE_TRUST
2169          1,
2170 #else
2171          0,
2172 #endif
2173       },
2174       {
2175          "FEATURE_ZLIB",
2176 #ifdef FEATURE_ZLIB
2177          1,
2178 #else
2179          0,
2180 #endif
2181       },
2182       {
2183          "FEATURE_DYNAMIC_PCRE",
2184 #ifdef FEATURE_DYNAMIC_PCRE
2185          1,
2186 #else
2187          0,
2188 #endif
2189       },
2190       {
2191          "FEATURE_EXTENDED_STATISTICS",
2192 #ifdef FEATURE_EXTENDED_STATISTICS
2193          1,
2194 #else
2195          0,
2196 #endif
2197       },
2198       {
2199          "FEATURE_PCRE_HOST_PATTERNS",
2200 #ifdef FEATURE_PCRE_HOST_PATTERNS
2201          1,
2202 #else
2203          0,
2204 #endif
2205       }
2206    };
2207
2208    for (i = 0; i < SZ(features); i++)
2209    {
2210       err = map_conditional(exports, features[i].name, features[i].is_available);
2211       if (err)
2212       {
2213          break;
2214       }
2215    }
2216
2217    return err;
2218
2219 }
2220
2221
2222 /*********************************************************************
2223  *
2224  * Function    :  cgi_show_file
2225  *
2226  * Description :  CGI function that shows the content of a
2227  *                configuration file.
2228  *
2229  * Parameters  :
2230  *          1  :  csp = Current client state (buffers, headers, etc...)
2231  *          2  :  rsp = http_response data structure for output
2232  *          3  :  parameters = map of cgi parameters
2233  *
2234  * CGI Parameters :
2235  *        file :  Which file to show.  Only first letter is checked,
2236  *                valid values are:
2237  *                - "a"ction file
2238  *                - "r"egex
2239  *                - "t"rust
2240  *                Default is to show menu and other information.
2241  *
2242  * Returns     :  JB_ERR_OK on success
2243  *                JB_ERR_MEMORY on out-of-memory error.
2244  *
2245  *********************************************************************/
2246 static jb_err cgi_show_file(struct client_state *csp,
2247                             struct http_response *rsp,
2248                             const struct map *parameters)
2249 {
2250    unsigned i;
2251    const char * filename = NULL;
2252    char * file_description = NULL;
2253
2254    assert(csp);
2255    assert(rsp);
2256    assert(parameters);
2257
2258    switch (*(lookup(parameters, "file")))
2259    {
2260    case 'a':
2261       if (!get_number_param(csp, parameters, "index", &i) && i < MAX_AF_FILES && csp->actions_list[i])
2262       {
2263          filename = csp->actions_list[i]->filename;
2264          file_description = "Actions File";
2265       }
2266       break;
2267
2268    case 'f':
2269       if (!get_number_param(csp, parameters, "index", &i) && i < MAX_AF_FILES && csp->rlist[i])
2270       {
2271          filename = csp->rlist[i]->filename;
2272          file_description = "Filter File";
2273       }
2274       break;
2275
2276 #ifdef FEATURE_TRUST
2277    case 't':
2278       if (csp->tlist)
2279       {
2280          filename = csp->tlist->filename;
2281          file_description = "Trust File";
2282       }
2283       break;
2284 #endif /* def FEATURE_TRUST */
2285    }
2286
2287    if (NULL != filename)
2288    {
2289       struct map *exports;
2290       char *s;
2291       jb_err err;
2292       size_t length;
2293
2294       exports = default_exports(csp, "show-status");
2295       if (NULL == exports)
2296       {
2297          return JB_ERR_MEMORY;
2298       }
2299
2300       if (map(exports, "file-description", 1, file_description, 1)
2301         || map(exports, "filepath", 1, html_encode(filename), 0))
2302       {
2303          free_map(exports);
2304          return JB_ERR_MEMORY;
2305       }
2306
2307       err = load_file(filename, &s, &length);
2308       if (JB_ERR_OK != err)
2309       {
2310          if (map(exports, "contents", 1, "<h1>ERROR OPENING FILE!</h1>", 1))
2311          {
2312             free_map(exports);
2313             return JB_ERR_MEMORY;
2314          }
2315       }
2316       else
2317       {
2318          s = html_encode_and_free_original(s);
2319          if (NULL == s)
2320          {
2321             free_map(exports);
2322             return JB_ERR_MEMORY;
2323          }
2324
2325          if (map(exports, "contents", 1, s, 0))
2326          {
2327             free_map(exports);
2328             return JB_ERR_MEMORY;
2329          }
2330       }
2331
2332       return template_fill_for_cgi(csp, "show-status-file", exports, rsp);
2333    }
2334
2335    return JB_ERR_CGI_PARAMS;
2336 }
2337
2338
2339 /*********************************************************************
2340  *
2341  * Function    :  load_file
2342  *
2343  * Description :  Loads a file into a buffer.
2344  *
2345  * Parameters  :
2346  *          1  :  filename = Name of the file to be loaded.
2347  *          2  :  buffer   = Used to return the file's content.
2348  *          3  :  length   = Used to return the size of the file.
2349  *
2350  * Returns     :  JB_ERR_OK in case of success,
2351  *                JB_ERR_FILE in case of ordinary file loading errors
2352  *                            (fseek() and ftell() errors are fatal)
2353  *                JB_ERR_MEMORY in case of out-of-memory.
2354  *
2355  *********************************************************************/
2356 static jb_err load_file(const char *filename, char **buffer, size_t *length)
2357 {
2358    FILE *fp;
2359    long ret;
2360    jb_err err = JB_ERR_OK;
2361
2362    fp = fopen(filename, "rb");
2363    if (NULL == fp)
2364    {
2365       log_error(LOG_LEVEL_ERROR, "Failed to open %s: %E", filename);
2366       return JB_ERR_FILE;
2367    }
2368
2369    /* Get file length */
2370    if (fseek(fp, 0, SEEK_END))
2371    {
2372       log_error(LOG_LEVEL_FATAL,
2373          "Unexpected error while fseek()ing to the end of %s: %E",
2374          filename);
2375    }
2376    ret = ftell(fp);
2377    if (-1 == ret)
2378    {
2379       log_error(LOG_LEVEL_FATAL,
2380          "Unexpected ftell() error while loading %s: %E",
2381          filename);
2382    }
2383    *length = (size_t)ret;
2384
2385    /* Go back to the beginning. */
2386    if (fseek(fp, 0, SEEK_SET))
2387    {
2388       log_error(LOG_LEVEL_FATAL,
2389          "Unexpected error while fseek()ing to the beginning of %s: %E",
2390          filename);
2391    }
2392
2393    *buffer = zalloc_or_die(*length + 1);
2394
2395    if (1 != fread(*buffer, *length, 1, fp))
2396    {
2397       /*
2398        * May theoretically happen if the file size changes between
2399        * fseek() and fread() because it's edited in-place. Privoxy
2400        * and common text editors don't do that, thus we just fail.
2401        */
2402       log_error(LOG_LEVEL_ERROR,
2403          "Couldn't completely read file %s.", filename);
2404       freez(*buffer);
2405       err = JB_ERR_FILE;
2406    }
2407
2408    fclose(fp);
2409
2410    return err;
2411
2412 }
2413
2414
2415 /*
2416   Local Variables:
2417   tab-width: 3
2418   end:
2419 */