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