Add an option to also gather statistics about how many request where made per host.
[privoxy.git] / tools / privoxy-log-parser.pl
1 #!/usr/bin/perl
2
3 ################################################################################
4 # privoxy-log-parser
5 #
6 # A parser for Privoxy log messages. For incomplete documentation run
7 # perldoc privoxy-log-parser(.pl), for fancy screenshots see:
8 #
9 # http://www.fabiankeil.de/sourcecode/privoxy-log-parser/
10 #
11 # $Id: privoxy-log-parser.pl,v 1.99 2010/11/08 17:51:54 fabiankeil Exp $
12 #
13 # TODO:
14 #       - LOG_LEVEL_CGI, LOG_LEVEL_ERROR, LOG_LEVEL_WRITE content highlighting
15 #       - create fancy statistics
16 #       - grep through Privoxy sources to find unsupported log messages
17 #       - hunt down substitutions that match content from variables which
18 #         can contain stuff like ()?'[]
19 #       - replace $h{'foo'} with h('foo') where possible
20 #       - hunt down XXX comments instead of just creating them
21 #       - add example log lines for every regex and mark them up for
22 #         regression testing
23 #       - Handle incomplete input without Perl warning about undefined variables.
24 #       - Use generic highlighting function that takes a regex and the
25 #         hash key as input.
26 #       - Add --compress and --decompress options.
27 #
28 # Copyright (c) 2007-2010 Fabian Keil <fk@fabiankeil.de>
29 #
30 # Permission to use, copy, modify, and distribute this software for any
31 # purpose with or without fee is hereby granted, provided that the above
32 # copyright notice and this permission notice appear in all copies.
33 #
34 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
35 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
36 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
37 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
38 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
39 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
40 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
41 ################################################################################
42
43 use strict;
44 use warnings;
45 use Getopt::Long;
46
47 use constant {
48     PRIVOXY_LOG_PARSER_VERSION => '0.6',
49     # Feel free to mess with these ...
50     DEFAULT_BACKGROUND => 'black',  # Choose registered colour (like 'black')
51     DEFAULT_TEXT_COLOUR => 'white', # Choose registered colour (like 'black')
52     HEADER_DEFAULT_COLOUR => 'yellow',
53     REGISTER_HEADERS_WITH_THE_SAME_COLOUR => 1,
54
55     CLI_OPTION_DEFAULT_TO_HTML_OUTPUT => 0,
56     CLI_OPTION_TITLE => 'Privoxy-Log-Parser in da house',
57     CLI_OPTION_NO_EMBEDDED_CSS => 0,
58     CLI_OPTION_NO_MSECS => 0,
59     CLI_OPTION_NO_SYNTAX_HIGHLIGHTING => 0,
60     CLI_OPTION_SHORTEN_THREAD_IDS => 0,
61     CLI_OPTION_SHOW_INEFFECTIVE_FILTERS => 0,
62     CLI_OPTION_ACCEPT_UNKNOWN_MESSAGES => 0,
63     CLI_OPTION_STATISTICS => 0,
64     CLI_OPTION_URL_STATISTICS_THRESHOLD => 0,
65     CLI_OPTION_HOST_STATISTICS_THRESHOLD => 0,
66
67     SUPPRESS_SUCCEEDED_FILTER_ADDITIONS => 1,
68     SHOW_SCAN_INTRO => 0,
69     SHOW_FILTER_READIN_IN => 0,
70     SUPPRESS_EMPTY_LINES => 1,
71     SUPPRESS_SUCCESSFUL_CONNECTIONS => 1,
72     SUPPRESS_ACCEPTED_CONNECTIONS => 1,
73     SUPPRESS_GIF_NOT_CHANGED => 1,
74     SUPPRESS_NEED_TO_DE_CHUNK_FIRST => 1,
75
76     DEBUG_HEADER_REGISTERING => 0,
77     DEBUG_HEADER_HIGHLIGHTING => 0,
78     DEBUG_TICKS => 0,
79     DEBUG_PAINT_IT => 0,
80     DEBUG_SUPPRESS_LOG_MESSAGES => 0,
81
82     PUNISH_MISSING_LOG_KNOWLEDGE_WITH_DEATH => 0,
83     PUNISH_MISSING_HIGHLIGHT_KNOWLEDGE_WITH_DEATH => 1,
84
85     LOG_UNPARSED_LINES_TO_EXTRA_FILE => 0,
86     ERROR_LOG_FILE => '/var/log/privoxy-log-parser',
87
88     # You better leave these alone unless you know what you're doing.
89     COLOUR_RESET      => "\033[0;0m",
90     ESCAPE => "\033[",
91 };
92
93 # For performance reasons, these are global.
94
95 my $t;
96 my %req; # request data from previous lines
97 my %h;
98 my %thread_colours;
99 my @all_colours;
100 my @time_colours;
101 my $thread_colour_index = 0;
102 my $header_colour_index = 0;
103 my $time_colour_index = 0;
104 my %header_colours;
105 my $no_special_header_highlighting;
106 my %reason_colours;
107 my %h_colours;
108 my $header_highlight_regex = '';
109
110 my $html_output_mode;
111 my $no_msecs_mode; # XXX: should probably be removed
112 my $shorten_thread_ids;
113 my $line_end;
114
115 sub prepare_our_stuff () {
116
117     # Syntax Higlight hash
118     @all_colours = (
119         'red', 'green', 'brown', 'blue', 'purple', 'cyan',
120         'light_gray', 'light_red', 'light_green', 'yellow',
121         'light_blue', 'pink', 'light_cyan', 'white'
122     );
123
124     %h = (
125         # LOG_LEVEL
126         Info            => 'blue',
127         Header          => 'green',
128         Filter          => 'purple', # XXX: Used?
129         'Re-Filter'     => 'purple',
130         Connect         => 'brown',
131         Request         => 'light_cyan',
132         CGI             => 'light_green',
133         Redirect        => 'cyan',
134         Error           => 'light_red',
135         Crunch          => 'cyan',
136         'Fatal error'   => 'light_red',
137         'Gif-Deanimate' => 'blue',
138         Force           => 'red',
139         Writing         => 'light_green',
140         Received        => 'yellow',
141         # ----------------------
142         URL                  => 'yellow',
143         path                 => 'brown',
144         request_             => 'brown', # host+path but no protocol
145         'ip-address'         => 'yellow',
146         Number               => 'yellow',
147         Standard             => 'reset',
148         Truncation           => 'light_red',
149         Status               => 'brown',
150         Timestamp            => 'brown',
151         Crunching            => 'light_red',
152         crunched             => 'light_red',
153         'Request-Line'       => 'pink',
154         method               => 'purple',
155         destination          => 'yellow',
156         'http-version'       => 'pink',
157         'crunch-pattern'     => 'pink',
158         not                  => 'brown',
159         file                 => 'brown',
160         signal               => 'yellow',
161         version              => 'green',
162         'program-name'       => 'cyan',
163         port                 => 'red',
164         host                 => 'red',
165         warning              => 'light_red',
166         debug                => 'light_red',
167         filter               => 'green',
168         tag                  => 'green',
169         tagger               => 'green',
170         'status-message'     => 'light_cyan',
171         'status-code'        => 'yellow',
172         'invalid-request'    => 'light_red',
173         'hits'               => 'yellow',
174         error                => 'light_red',
175         'rewritten-URL'      => 'light_red',
176         'pcrs-delimiter'     => 'light_red',
177         'ignored'            => 'light_red',
178         'action-bits-update' => 'light_red',
179         'configuration-line' => 'red',
180         'content-type'       => 'yellow',
181     );
182
183     %h_colours = %h;
184
185     # Header colours need their own hash so the keys can be accessed properly
186     %header_colours = (
187         # Prefilled with headers that should not appear with default header colours
188         Cookie => 'light_red',
189         'Set-Cookie' => 'light_red',
190         Warning => 'light_red',
191         Default => HEADER_DEFAULT_COLOUR,
192     );
193
194     # Crunch reasons need their own hash as well
195     %reason_colours = (
196         'Unsupported HTTP feature'               => 'light_red',
197         Blocked                                  => 'light_red',
198         Untrusted                                => 'light_red',
199         Redirected                               => 'green',
200         'CGI Call'                               => 'white',
201         'DNS failure'                            => 'red',
202         'Forwarding failed'                      => 'light_red',
203         'Connection failure'                     => 'light_red',
204         'Out of memory (may mask other reasons)' => 'light_red',
205         'No reason recorded'                     => 'light_red',
206     );
207
208     @time_colours = ('white', 'light_gray');
209
210     # Translate highlight strings into highlight code
211     prepare_highlight_hash(\%header_colours);
212     prepare_highlight_hash(\%reason_colours);
213     prepare_highlight_hash(\%h);
214     prepare_colour_array(\@all_colours);
215     prepare_colour_array(\@time_colours);
216     init_css_colours();
217
218     init_stats();
219 }
220
221 sub paint_it ($) {
222 ###############################################################
223 # Takes a colour string and returns an ANSI escape sequence
224 # (unless --no-syntax-highlighting is used).
225 # XXX: The Rolling Stones reference has to go.
226 ###############################################################
227
228     my $colour = shift @_;
229
230     return "" if cli_option_is_set('no-syntax-highlighting');
231
232     my %light = (
233         black       => 0,
234         red         => 0,
235         green       => 0,
236         brown       => 0,
237         blue        => 0,
238         purple      => 0,
239         cyan        => 0,
240         light_gray  => 0,
241         gray        => 0,
242         dark_gray   => 1,
243         light_red   => 1,
244         light_green => 1,
245         yellow      => 1,
246         light_blue  => 1,
247         pink        => 1,
248         light_cyan  => 1,
249         white       => 1,
250     );
251
252     my %text = (
253         black       => 30,
254         red         => 31,
255         green       => 32,
256         brown       => 33,
257         blue        => 34,
258         purple      => 35,
259         cyan        => 36,
260         gray        => 37,
261         light_gray  => 37,
262         dark_gray   => 30,
263         light_red   => 31,
264         light_green => 32,
265         yellow      => 33,
266         light_blue  => 34,
267         pink        => 35,
268         light_cyan  => 36,
269         white       => 37,
270     );
271
272     my $bg_code = get_background();
273     my $colour_code;
274     our $default = default_colours();
275
276     if (defined($text{$colour})) {
277         $colour_code  = ESCAPE;
278         $colour_code .= $text{$colour};
279         $colour_code .= ";";
280         $colour_code .= $light{$colour} ? "1" : "2";
281         $colour_code .= ";";
282         $colour_code .= $bg_code;
283         $colour_code .= "m";
284         debug_message $colour . " is \'" . $colour_code . $colour . $default . "\'" if DEBUG_PAINT_IT;
285
286     } elsif ($colour =~ /reset/) {
287
288         $colour_code = default_colours();
289
290     } else {
291
292         die "What's $colour supposed to mean?\n";
293     }
294
295     return $colour_code;
296 }
297
298 sub get_semantic_html_markup ($) {
299 ###############################################################
300 # Takes a string and returns a span element
301 ###############################################################
302
303     my $type = shift @_;
304     my $code;
305
306     if ($type =~ /Standard/) {
307         $code = '</span>';
308     } else {
309         $type = lc($type);
310         $code = '<span title="' . $type . '" class="' . $type . '">';
311     }
312
313     return $code;
314 }
315
316 sub cli_option_is_set ($) {
317
318     our %cli_options;
319     my $cli_option = shift;
320
321     die "Unknown CLI option: $cli_option" unless defined $cli_options{$cli_option};
322
323     return $cli_options{$cli_option};
324 }
325
326 sub get_html_title () {
327
328     our %cli_options;
329     return $cli_options{'title'};
330
331 }
332
333 sub init_css_colours() {
334
335     our %css_colours = (
336         black       => "000",
337         red         => "F00",
338         green       => "0F0",
339         brown       => "C90",
340         blue        => "0F0",
341         purple      => "F06", # XXX: wrong
342         cyan        => "F09", # XXX: wrong
343         light_gray  => "999",
344         gray        => "333",
345         dark_gray   => "222",
346         light_red   => "F33",
347         light_green => "33F",
348         yellow      => "FF0",
349         light_blue  => "30F",
350         pink        => "F0F",
351         light_cyan  => "66F",
352         white       => "FFF",
353     );
354 }
355
356 sub get_css_colour ($) {
357
358    our %css_colours;
359    my $colour = shift;
360
361    die "What's $colour supposed to mean?\n" unless defined($css_colours{$colour});
362
363    return '#' . $css_colours{$colour};
364 }
365
366 sub get_css_line ($) {
367
368     my $class = shift;
369     my $css_line;
370
371     $css_line .= '.' . lc($class) . ' {'; # XXX: lc() shouldn't be necessary
372     die "What's $class supposed to mean?\n" unless defined($h_colours{$class});
373     $css_line .= 'color:' . get_css_colour($h_colours{$class}) . ';';
374     $css_line .= 'background-color:' . get_css_colour(DEFAULT_BACKGROUND) . ';';
375     $css_line .= '}' . "\n";
376
377     return $css_line;
378 }
379
380 sub get_css_line_for_colour ($) {
381
382     my $colour = shift;
383     my $css_line;
384
385     $css_line .= '.' . lc($colour) . ' {'; # XXX: lc() shouldn't be necessary
386     $css_line .= 'color:' . get_css_colour($colour) . ';';
387     $css_line .= 'background-color:' . get_css_colour(DEFAULT_BACKGROUND) . ';';
388     $css_line .= '}' . "\n";
389
390     return $css_line;
391 }
392
393 # XXX: Wrong solution
394 sub get_missing_css_lines () {
395
396     my $css_line;
397
398     $css_line .= '.' . 'default' . ' {';
399     $css_line .= 'color:' . HEADER_DEFAULT_COLOUR . ';';
400     $css_line .= 'background-color:' . get_css_colour(DEFAULT_BACKGROUND) . ';';
401     $css_line .= '}' . "\n";
402
403     return $css_line;
404 }
405
406 sub get_css () {
407
408     our %css_colours; #XXX: Wrong solution
409
410     my $css = '';
411
412     $css .= '.privoxy-log {';
413     $css .= 'color:' . get_css_colour(DEFAULT_TEXT_COLOUR) . ';';
414     $css .= 'background-color:' . get_css_colour(DEFAULT_BACKGROUND) . ';';
415     $css .= '}' . "\n";
416
417     foreach my $key (keys %h_colours) {
418
419         next if ($h_colours{$key} =~ m/reset/); #XXX: Wrong solution.
420         $css .= get_css_line($key);
421
422     }
423
424     foreach my $colour (keys %css_colours) {
425
426         $css .= get_css_line_for_colour($colour);
427
428     }
429
430     $css .= get_missing_css_lines(); #XXX: Wrong solution
431
432     return $css;
433 }
434
435 sub print_intro () {
436
437     my $intro = '';
438
439     if (cli_option_is_set('html-output')) {
440
441         my $title = get_html_title();
442
443         $intro .= '<html><head>';
444         $intro .= '<title>' . $title . '</title>';
445         $intro .= '<style>' . get_css() . '</style>' unless cli_option_is_set('no-embedded-css');
446         $intro .= '</head><body>';
447         $intro .= '<h1>' . $title . '</h1><p class="privoxy-log">';
448
449         print $intro;
450     }
451 }
452
453 sub print_outro () {
454
455     my $outro = '';
456
457     if (cli_option_is_set('html-output')) {
458
459         $outro = '</p></body></html>';
460         print $outro;
461
462     }
463 }
464
465 sub get_line_end () {
466     return cli_option_is_set('html-output') ? "<br>\n" : "\n";
467 }
468
469 sub get_colour_html_markup ($) {
470 ###############################################################
471 # Takes a colour string a span element. XXX: WHAT?
472 # XXX: This function shouldn't be necessary, the
473 # markup should always be semantically correct.
474 ###############################################################
475
476     my $type = shift @_;
477     my $code;
478
479     if ($type =~ /Standard/) {
480         $code = '</span>';
481     } else {
482         $code = '<span class="' . lc($type) . '">';
483     }
484
485     return $code;
486 }
487
488 sub default_colours () {
489     # XXX: Properly
490     our $bg_code;
491     return reset_colours();
492 }
493
494 sub show_colours () {
495     # XXX: Implement
496 }
497
498 sub reset_colours () {
499     return ESCAPE . "0m";
500 }
501
502 sub set_background ($){
503
504     my $colour = shift;
505     our $bg_code;
506     my %backgrounds = (
507               black       => "40",
508               red         => "41",
509               green       => "42",
510               brown       => "43",
511               blue        => "44",
512               magenta     => "45",
513               cyan        => "46",
514               white       => "47",
515               default     => "49",
516     );
517
518     if (defined($backgrounds{$colour})) {
519         $bg_code = $backgrounds{$colour};
520     } else {
521         die "Invalid background colour: " . $colour;
522     }
523 }
524
525 sub get_background (){
526     return our $bg_code;
527 }
528
529 sub prepare_highlight_hash ($) {
530     my $ref = shift;
531
532     foreach my $key (keys %$ref) {
533         $$ref{$key} = $html_output_mode ?
534             get_semantic_html_markup($key) :
535             paint_it($$ref{$key});
536     }
537 }
538
539 sub prepare_colour_array ($) {
540     my $ref = shift;
541
542     foreach my $i (0 ... @$ref - 1) {
543         $$ref[$i] = $html_output_mode ?
544             get_colour_html_markup($$ref[$i]) :
545             paint_it($$ref[$i]);
546     }
547 }
548
549 sub found_unknown_content ($) {
550
551     my $unknown = shift;
552     my $message;
553
554     return if cli_option_is_set('accept-unknown-messages');
555
556     return if ($unknown =~ /\[too long, truncated\]$/);
557
558     $message = "found_unknown_content: Don't know how to highlight: ";
559     # Break line so the log file can later be parsed as Privoxy log file again
560     $message .= '"' . $unknown . '"' . " in:\n";
561     $message .= $req{$t}{'log-message'};
562     debug_message($message);
563     log_parse_error($req{$t}{'log-message'});
564
565     die "Unworthy content parser" if PUNISH_MISSING_LOG_KNOWLEDGE_WITH_DEATH;
566 }
567
568 sub log_parse_error ($) {
569
570     my $message = shift;
571
572     if (LOG_UNPARSED_LINES_TO_EXTRA_FILE) {
573         open(ERRORLOG, ">>" . ERROR_LOG_FILE) || die "Writing " . ERROR_LOG_FILE . " failed";
574         print ERRORLOG $message;
575         close(ERRORLOG);
576     }
577 }
578
579 sub debug_message (@) {
580     my @message = @_;
581
582     print $h{'debug'} . "@message" . $h{'Standard'} . "\n";
583 }
584
585 ################################################################################
586 # highlighter functions that aren't loglevel-specific
587 ################################################################################
588
589 sub h ($) {
590
591     # Get highlight marker
592     my $highlight = shift; # XXX: Stupid name;
593     my $result = '';
594     my $message;
595
596     if (defined($highlight)) {
597
598         $result = $h{$highlight};
599
600     } else {
601
602         $message = "h: Don't recognize highlighter $highlight.";
603         debug_message($message);
604         log_parser_error($message);
605         die "Unworthy highlighter function" if PUNISH_MISSING_HIGHLIGHT_KNOWLEDGE_WITH_DEATH;
606     }
607
608     return $result;
609 }
610
611 sub highlight_known_headers ($) {
612
613     my $content = shift;
614
615     debug_message("Searching $content for things to highlight.") if DEBUG_HEADER_HIGHLIGHTING;
616
617     if ($content =~ m/(?<=\s)($header_highlight_regex):/) {
618         my $header = $1;
619         $content =~ s@(?<=[\s|'])($header)(?=:)@$header_colours{$header}$1$h{'Standard'}@ig;
620         debug_message("Highlighted '$header' in '$content'") if DEBUG_HEADER_HIGHLIGHTING;
621     }
622
623     return $content;
624 }
625
626 sub highlight_matched_request_line ($$) {
627
628     my $result = shift; # XXX: Stupid name;
629     my $regex = shift;
630     if ($result =~ m@(.*)($regex)(.*)@) {
631         $result = $1 . highlight_request_line($2) . $3
632     }
633     return $result;
634 }
635
636 sub highlight_request_line ($) {
637
638     my $rl = shift;
639     my ($method, $url, $http_version);
640
641     #GET http://images.sourceforge.net/sfx/icon_warning.gif HTTP/1.1
642     if ($rl =~ m/Invalid request/) {
643
644         $rl = h('invalid-request') . $rl . h('Standard');
645
646     } elsif ($rl =~ m/^([-\w]+) (.*) (HTTP\/\d\.\d)/) {
647
648         # XXX: might not match in case of HTTP method fuzzing.
649         # XXX: save these: ($method, $path, $http_version) = ($1, $2, $3);
650         $rl =~ s@^(\w+)@$h{'method'}$1$h{'Standard'}@;
651         if ($rl =~ /http:\/\//) {
652             $rl = highlight_matched_url($rl, '[^\s]*(?=\sHTTP)');
653         } else {
654             $rl = highlight_matched_pattern($rl, 'request_', '[^\s]*(?=\sHTTP)');
655         }
656
657         $rl =~ s@(HTTP\/\d\.\d)$@$h{'http-version'}$1$h{'Standard'}@;
658
659     } elsif ($rl =~ m/\.\.\. \[too long, truncated\]$/) {
660
661         $rl =~ s@^(\w+)@$h{'method'}$1$h{'Standard'}@;
662         $rl = highlight_matched_url($rl, '[^\s]*(?=\.\.\.)');
663
664     } elsif ($rl =~ m/^ $/) {
665
666         $rl = h('error') . "No request line specified!" . h('Standard');
667
668     } else {
669
670         debug_message ("Can't parse request line: $rl");
671
672     }
673
674     return $rl;
675 }
676
677 sub highlight_response_line ($) {
678
679     my $rl = shift;
680     my ($http_version, $status_code, $status_message);
681
682     #HTTP/1.1 200 OK
683     #ICY 200 OK
684
685     # TODO: Mark different status codes differently
686
687     if ($rl =~ m/((?:HTTP\/\d\.\d|ICY)) (\d+) (.*)/) {
688         ($http_version, $status_code, $status_message) = ($1, $2, $3);
689     } else {
690         debug_message ("Can't parse response line: $rl") and die 'Fix this';
691     }
692
693     # Rebuild highlighted
694     $rl= "";
695     $rl .= h('http-version') . $http_version . h('Standard');
696     $rl .= " ";
697     $rl .= h('status-code') . $status_code . h('Standard');
698     $rl .= " ";
699     $rl .= h('status-message') . $status_message . h('Standard');
700
701     return $rl;
702 }
703
704 sub highlight_matched_url ($$) {
705
706     my $result = shift; # XXX: Stupid name;
707     my $regex = shift;
708
709     #print "Got $result, regex ($regex)\n";
710
711     if ($result =~ m@(.*?)($regex)(.*)@) {
712         $result = $1 . highlight_url($2) . $3;
713         #print "Now the result is $result\n";
714     }
715
716     return $result;
717 }
718
719 sub highlight_matched_host ($$) {
720
721     my ($result, $regex) = @_; # XXX: result ist stupid name;
722
723     if ($result =~ m@(.*?)($regex)(.*)@) {
724         $result = $1 . $h{host} . $2 . $h{Standard} . $3;
725     }
726
727     return $result;
728 }
729
730 sub highlight_matched_pattern ($$$) {
731
732     my $result = shift; # XXX: Stupid name;
733     my $key = shift;
734     my $regex = shift;
735
736     die "Unknown key $key" unless defined $h{$key};
737
738     if ($result =~ m@(.*?)($regex)(.*)@) {
739         $result = $1 . h($key) . $2 . h('Standard') . $3;
740     }
741
742     return $result;
743 }
744
745 sub highlight_matched_path ($$) {
746
747     my $result = shift; # XXX: Stupid name;
748     my $regex = shift;
749
750     if ($result =~ m@(.*?)($regex)(.*)@) {
751         $result = $1 . h('path') . $2 . h('Standard') . $3;
752     }
753
754     return $result;
755 }
756
757 sub highlight_url ($) {
758
759     my $url = shift;
760
761     if ($html_output_mode) {
762
763         $url = '<a href="' . $url . '">' . $url . '</a>';
764
765     } else {
766
767         $url = h('URL') . $url . h('Standard');
768
769     }
770
771     return $url;
772 }
773
774 sub update_header_highlight_regex ($) {
775
776     my $header = shift;
777     my $headers = join ('|', keys %header_colours);
778
779     $header_highlight_regex = qr/$headers/;
780     print "Registering '$header'\n" if DEBUG_HEADER_HIGHLIGHTING;
781 }
782
783 ################################################################################
784 # loglevel-specific highlighter functions
785 ################################################################################
786
787 sub handle_loglevel_header ($) {
788
789     my $c = shift;
790
791     if ($c =~ /^scan:/) {
792
793         if ($c =~ m/^scan: ([^: ]+):/) {
794
795             # Register new headers
796             # scan: Accept: image/png,image/*;q=0.8,*/*;q=0.5
797             my $header = $1;
798             if (!defined($header_colours{$header}) and $header =~ /^[\d\w-]*$/) {
799                 debug_message "Registering previously unknown header $1" if DEBUG_HEADER_REGISTERING;
800
801                 if (REGISTER_HEADERS_WITH_THE_SAME_COLOUR) {
802                     $header_colours{$header} =  $header_colours{'Default'};
803                 } else {
804                     $header_colours{$header} = $all_colours[$header_colour_index % @all_colours];
805                     $header_colour_index++;
806                 }
807                 update_header_highlight_regex($header);
808             }
809
810         } elsif ($c =~ m/^(scan: )(\w+ .+ HTTP\/\d\.\d)/) {
811
812             # scan: HTTP/1.1 200 OK
813             $c = $1 . highlight_request_line($2);
814
815         } elsif ($c =~ m/^(scan: )((?:HTTP\/\d\.\d|ICY) (\d+) (.*))/) {
816
817             # Server response line
818             $req{$t}{'response_line'} = $2;
819             $req{$t}{'status_code'} = $3;
820             $req{$t}{'status_message'} = $4;
821             $c = $1 . highlight_response_line($req{$t}{'response_line'});
822         }
823
824     } elsif ($c =~ m/^Crunching (?:server|client) header: .* \(contains: ([^\)]*)\)/) {
825
826         # Crunching server header: Set-Cookie: trac_form_token=d5308c34e16d15e9e301a456; (contains: Cookie:)
827         $c =~ s@(?<=contains: )($1)@$h{'crunch-pattern'}$1$h{'Standard'}@;
828         $c =~ s@(Crunching)@$h{$1}$1$h{'Standard'}@;
829
830     } elsif ($c =~ m/^New host is: ([^\s]*)\./) {
831
832         # New host is: trac.vidalia-project.net. Crunching Referer: http://www.vidalia-project.net/!
833         $c = highlight_matched_host($c, '(?<=New host is: )[^\s]+(?=\.)');
834         $c = highlight_matched_url($c, '(?<=Crunching Referer: )[^\s!]+');
835
836     } elsif ($c =~ m/^Text mode enabled by force. (Take cover)!/) {
837
838         # Text mode enabled by force. Take cover!
839         $c =~ s@($1)@$h{'warning'}$1$h{'Standard'}@;
840
841     } elsif ($c =~ m/^(New HTTP Request-Line: )(.*)/) {
842
843         # New HTTP Request-Line: GET http://www.privoxy.org/ HTTP/1.1
844         $c = $1 . highlight_request_line($2);
845
846     } elsif ($c =~ m/^Adjust(ed)? Content-Length to \d+/) {
847
848         # Adjusted Content-Length to 2132
849         # Adjust Content-Length to 33533
850         $c =~ s@(?<=Content-Length to )(\d+)@$h{'Number'}$1$h{'Standard'}@;
851         $c = highlight_known_headers($c);
852
853     } elsif ($c =~ m/^Destination extracted from "Host:" header. New request URL:/) {
854
855         # Destination extracted from "Host:" header. New request URL: http://www.cccmz.de/~ridcully/blog/
856         $c = highlight_matched_url($c, '(?<=New request URL: ).*');
857
858     } elsif ($c =~ m/^Couldn\'t parse:/) {
859
860         # XXX: These should probable be logged with LOG_LEVEL_ERROR
861         # Couldn't parse: If-Modified-Since: Wed, 21 Mar 2007 16:34:50 GMT (crunching!)
862         # Couldn't parse: at, 24 Mar 2007 13:46:21 GMT in If-Modified-Since: Sat, 24 Mar 2007 13:46:21 GMT (crunching!)
863         $c =~ s@^(Couldn\'t parse)@$h{'error'}$1$h{'Standard'}@;
864
865     } elsif ($c =~ /^Tagger \'([^\']*)\' added tag \'([^\']*)\'/ or
866              $c =~ m/^Adding tag \'([^\']*)\' created by header tagger \'([^\']*)\'/) {
867
868         # Adding tag 'GET request' created by header tagger 'method-man' (XXX: no longer used)
869         # Tagger 'revalidation' added tag 'REVALIDATION-REQUEST'. No action bit update necessary.
870         # Tagger 'revalidation' added tag 'REVALIDATION-REQUEST'. Action bits updated accordingly.
871
872         # XXX: Save tag and tagger
873
874         $c =~ s@(?<=^Tagger \')([^\']*)@$h{'tagger'}$1$h{'Standard'}@;
875         $c =~ s@(?<=added tag \')([^\']*)@$h{'tag'}$1$h{'Standard'}@;
876         $c =~ s@(?<=Action bits )(updated)@$h{'action-bits-update'}$1$h{'Standard'}@;
877         $no_special_header_highlighting = 1;
878
879     } elsif ($c =~ /^Tagger \'([^\']*)\' didn['']t add tag \'([^\']*)\'/) {
880
881         # Tagger 'revalidation' didn't add tag 'REVALIDATION-REQUEST'. Tag already present
882         # XXX: Save tag and tagger
883
884         $c =~ s@(?<=^Tagger \')([^\']*)@$h{'tag'}$1$h{'Standard'}@;
885         $c =~ s@(?<=didn['']t add tag \')([^\']*)@$h{'tagger'}$1$h{'Standard'}@;
886
887     } elsif ($c =~ m/^(?:scan:|Randomiz|addh:|Adding:|Removing:|Referer:|Modified:|Accept-Language header|[Cc]ookie)/
888           or $c =~ m/^(Text mode is already enabled|Denied request with NULL byte|Replaced:|add-unique:)/
889           or $c =~ m/^(Crunched (incoming|outgoing) cookie|Suppressed offer|Accepted the client)/
890           or $c =~ m/^(addh-unique|Referer forged to)/
891           or $c =~ m/^Downgraded answer to HTTP\/1.0/
892           or $c =~ m/^Parameter: \+hide-referrer\{[^\}]*\} is a bad idea, but I don\'t care./
893           or $c =~ m/^Referer (?:overwritten|replaced) with: Referer: / #XXX: should this be highlighted?
894           or $c =~ m/^Referer crunched!/
895           or $c =~ m/^crunched x-forwarded-for!/
896           or $c =~ m/^crunched From!/
897           or $c =~ m/^ modified$/
898           or $c =~ m/^Content filtering is enabled. Crunching:/
899           or $c =~ m/^force-text-mode overruled the client/
900           or $c =~ m/^Server time in the future\./
901           or $c =~ m/^content-disposition header crunched and replaced with:/i
902           or $c =~ m/^Reducing white space in /
903           or $c =~ m/^Ignoring single quote in /
904           or $c =~ m/^Converting tab to space in /
905           or $c =~ m/A HTTP\/1\.1 response without/
906           or $c =~ m/Disabled filter mode on behalf of the client/
907           or $c =~ m/Keeping the (?:server|client) header /
908           or $c =~ m/Content modified with no Content-Length header set/
909           or $c =~ m/^Appended client IP address to/
910           or $c =~ m/^Removing 'Connection: close' to imply keep-alive./
911           or $c =~ m/^keep-alive support is disabled/
912           or $c =~ m/^Continue hack in da house/
913             )
914     {
915         # XXX: Some of these may need highlighting
916
917         # Modified: User-Agent: Mozilla/5.0 (X11; U; SunOS i86pc; pl-PL; rv:1.8.1.1) Gecko/20070214 Firefox/2.0.0.1
918         # Accept-Language header crunched and replaced with: Accept-Language: pl-pl
919         # cookie 'Set-Cookie: eZSessionCookie=07bfec287c197440d299f81580593c3d; \
920         #  expires=Thursday, 12-Apr-07 15:16:18 GMT; path=/' send by \
921         #  http://wirres.net/article/articleview/4265/1/6/ appears to be using time format 1 (XXX: gone with the wind)
922         # Cookie rewritten to a temporary one: Set-Cookie: NSC_gffe-iuuq-mc-wtfswfs=8efb33a53660;path=/
923         # Text mode is already enabled
924         # Denied request with NULL byte(s) turned into line break(s)
925         # Replaced: 'Connection: Yo, home to Bel Air' with 'Connection: close'
926         # addh-unique: Host: people.freebsd.org
927         # Suppressed offer to compress content
928         # Crunched incoming cookie -- yum!
929         # Accepted the client's request to fetch without filtering.
930         # Crunched outgoing cookie: Cookie: PREF=ID=6cf0abd347b30262:TM=1173357617:LM=1173357617:S=jZypyyJ7LPiwFi1_
931         # addh-unique: Host: subkeys.pgp.net:11371
932         # Referer forged to: Referer: http://10.0.0.1/
933         # Downgraded answer to HTTP/1.0
934         # Parameter: +hide-referrer{pille-palle} is a bad idea, but I don't care.
935         # Referer overwritten with: Referer: pille-palle
936         # Referer replaced with: Referer: pille-palle
937         # crunched x-forwarded-for!
938         # crunched From!
939         #  modified # XXX: pretty stupid log message
940         # Content filtering is enabled. Crunching: 'Range: 1234-5678' to prevent range-mismatch problems
941         # force-text-mode overruled the client's request to fetch without filtering!
942         # Server time in the future.
943         # content-disposition header crunched and replaced with: content-disposition: filename=baz
944         # Content-Disposition header crunched and replaced with: content-disposition: filename=baz
945         # Reducing white space in 'X-LWS-Test: "This  is  quoted" this is not "this  is  " but " this again   is  not'
946         # Ignoring single quote in 'X-LWS-Test: "This  is  quoted" this is not "this  is  " but "  this again   is  not'
947         # Converting tab to space in 'X-LWS-Test:   "This  is  quoted" this   is  not "this  is  "  but  "\
948         #  this again   is  not'
949         # A HTTP/1.1 response without Connection header implies keep-alive.
950         # Disabled filter mode on behalf of the client.
951         # Keeping the server header 'Connection: keep-alive' around.
952         # Keeping the client header 'Connection: close' around. The connection will not be kept alive.
953         # Keeping the client header 'Connection: keep-alive' around. The connection will be kept alive if possible.
954         # Content modified with no Content-Length header set. Creating a fake one for adjustment later on.
955         # Appended client IP address to X-Forwarded-For: 10.0.0.2, 10.0.0.1
956         # Removing 'Connection: close' to imply keep-alive.
957         # keep-alive support is disabled. Crunching: Keep-Alive: 300.
958         # Continue hack in da house.
959
960     } elsif ($c =~ m/^scanning headers for:/) {
961
962         return '' unless SHOW_SCAN_INTRO;
963
964     } elsif ($c =~ m/^[Cc]runch(ing|ed)|crumble crunched:/) {
965         # crunched User-Agent!
966         # Crunching: Content-Encoding: gzip
967
968         $c =~ s@(Crunching|crunched)@$h{$1}$1$h{'Standard'}@;
969
970     } elsif ($c =~ m/^Offending request data with NULL bytes turned into \'°\' characters:/) {
971
972         # Offending request data with NULL bytes turned into '°' characters: Â°Â°n°°(°°°
973
974         $c = h('warning') . $c . h('Standard');
975
976     } elsif ($c =~ m/^(Transforming \")(.*?)(\" to \")(.*?)(\")/) {
977
978         # Transforming "Proxy-Authenticate: Basic realm="Correos Proxy Server"" to\
979         #  "Proxy-Authenticate: Basic realm="Correos Proxy Server""
980
981        $c =~ s@(?<=^Transforming \")(.*)(?=\" to)@$h{'Header'}$1$h{'Standard'}@;
982        $c =~ s@(?<=to \")(.*)(?=\")@$h{'Header'}$1$h{'Standard'}@;
983
984     } elsif ($c =~ m/^Removing empty header/) {
985
986         # Removing empty header
987         # Ignore for now
988
989     } elsif ($c =~ m/^Content-Type: .* not replaced/) {
990
991         # Content-Type: application/octet-stream not replaced. It doesn't look like text.\
992         #  Enable force-text-mode if you know what you're doing.
993         # XXX: Could highlight more here.
994         $c =~ s@(?<=^Content-Type: )(.*)(?= not replaced)@$h{'content-type'}$1$h{'Standard'}@;
995
996     } elsif ($c =~ m/^(Server|Client) keep-alive timeout is/) {
997
998        # Server keep-alive timeout is 5. Sticking with 10.
999        # Client keep-alive timeout is 20. Sticking with 10.
1000
1001        $c =~ s@(?<=timeout is )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1002        $c =~ s@(?<=Sticking with )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1003
1004     } elsif ($c =~ m/^Reducing keep-alive timeout/) {
1005
1006        # Reducing keep-alive timeout from 60 to 10.
1007
1008        $c =~ s@(?<= from )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1009        $c =~ s@(?<= to )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1010
1011     } else {
1012
1013         found_unknown_content($c);
1014     }
1015
1016     # Highlight headers
1017     unless ($c =~ m/^Transforming/) {
1018         $c = highlight_known_headers($c) unless $no_special_header_highlighting;
1019     }
1020
1021     return $c;
1022 }
1023
1024 sub handle_loglevel_re_filter ($) {
1025
1026     my $content = shift;
1027     my $c = $content;
1028     my $key;
1029
1030     if ($c =~ m/^(?:re_)?filtering ([^\s]+) \(size (\d+)\) with (?:filter )?\'?([^\s]+?)\'? produced (\d+) hits \(new size (\d+)\)/) {
1031
1032         # XXX: only the second version gets highlighted properly.
1033         # re_filtering www.lfk.de/favicon.ico (size 209) with filter untrackable-hulk produced 0 hits (new size 209).
1034         # filtering aci.blogg.de/ (size 37988) with 'blogg.de' produced 3 hits (new size 38057)
1035         $req{$t}{'content_source'} = $1;
1036         $req{$t}{'content_size'}   = $2;
1037         $req{$t}{'content_filter'} = $3;
1038         $req{$t}{'content_hits'}   = $4;
1039         $req{$t}{'new_content_size'} = $5;
1040         $req{$t}{'content_size_change'} = $req{$t}{'new_content_size'} - $req{$t}{'content_size'};
1041         #return '' if ($req{$t}{'content_hits'} == 0 && !cli_option_is_set('show-ineffective-filters'));
1042         if ($req{$t}{'content_hits'} == 0 and
1043             not (cli_option_is_set('show-ineffective-filters')
1044                  or ($req{$t}{'content_filter'} =~ m/^privoxy-filter-test$/))) {
1045                 return '';
1046         }
1047
1048         $c =~ s@(?<=\(size )(\d+)\)(?= with)@$h{'Number'}$1$h{'Standard'}@;
1049         $c =~ s@(?<=\(new size )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1050         $c =~ s@(?<=produced )(\d+)(?= hits)@$h{'Number'}$1$h{'Standard'}@;
1051
1052         $c =~ s@([^\s]+?)(\'? produced)@$h{'filter'}$1$h{'Standard'}$2@;
1053         $c = highlight_matched_host($c, '(?<=filtering )[^\s]+');
1054
1055         $c =~ s@\.$@ @;
1056         $c .= "(" . $h{'Number'};
1057         $c .= "+" if ($req{$t}{'content_size_change'} >= 0);
1058         $c .= $req{$t}{'content_size_change'} . $h{'Standard'} . ")";
1059         $content = $c;
1060
1061   } elsif ($c =~ /\.{3}$/
1062         and $c =~ m/^(?:re_)?filtering \'?(.*?)\'? \(size (\d*)\) with (?:filter )?\'?([^\s]*?)\'? ?\.{3}$/) {
1063
1064         # Used by Privoxy 3.0.5 and 3.0.6:
1065         # XXX: Fill in ...
1066         # Used by Privoxy 3.0.7:
1067         # filtering 'Connection: close' (size 17) with 'generic-content-ads' ...
1068
1069         $req{$t}{'filtered_header'} = $1;
1070         $req{$t}{'old_header_size'} = $2;
1071         $req{$t}{'header_filter_name'} = $3;
1072
1073         unless (cli_option_is_set('show-ineffective-filters') or
1074                 $req{$t}{'header_filter_name'} =~ m/^privoxy-filter-test$/) {
1075             return '';
1076         }
1077         $content =~ s@(?<=\(size )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1078         $content =~ s@($req{$t}{'header_filter_name'})@$h{'filter'}$1$h{'Standard'}@;
1079
1080     } elsif ($c =~ m/^ ?\.\.\. ?produced (\d*) hits \(new size (\d*)\)\./) {
1081
1082         # ...produced 0 hits (new size 23).
1083         #... produced 1 hits (new size 54).
1084
1085         $req{$t}{'header_filter_hits'} = $1;
1086         $req{$t}{'new_header_size'} = $2;
1087
1088         unless (cli_option_is_set('show-ineffective-filters') or
1089                 (defined($req{$t}{'header_filter_name'}) and
1090                  $req{$t}{'header_filter_name'} =~ m/^privoxy-filter-test$/)) {
1091
1092             if ($req{$t}{'header_filter_hits'} == 0 and
1093                 not (defined($req{$t}{'header_filter_name'}) and
1094                  $req{$t}{'header_filter_name'} =~ m/^privoxy-filter-test$/)) {
1095                 return '';
1096             }
1097             # Reformat including information from the intro
1098             $c = "'" . h('filter') . $req{$t}{'header_filter_name'} . h('Standard') . "'";
1099             $c .= " hit ";
1100             # XXX: Hide behind constant, it may be interesting if LOG_LEVEL_HEADER isn't enabled as well.
1101             # $c .= $req{$t}{'filtered_header'} . " ";
1102             $c .= h('Number') . $req{$t}{'header_filter_hits'}. h('Standard');
1103             $c .= ($req{$t}{'header_filter_hits'} == 1) ? " time, " : " times, ";
1104
1105             if ($req{$t}{'old_header_size'} !=  $req{$t}{'new_header_size'}) {
1106
1107                 $c .= "changing size from ";
1108                 $c .=  h('Number') . $req{$t}{'old_header_size'} . h('Standard');
1109                 $c .= " to ";
1110                 $c .= h('Number') . $req{$t}{'new_header_size'} . h('Standard');
1111                 $c .= ".";
1112
1113             } else {
1114
1115                 $c .= "keeping the size at " . $req{$t}{'old_header_size'};
1116
1117             }
1118
1119             # Highlight from last line (XXX: What?)
1120             # $c =~ s@(?<=produced )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1121             # $c =~ s@($req{$t}{'header_filter_name'})@$h{'filter'}$1$h{'Standard'}@;
1122
1123         } else {
1124
1125            # XXX: Untested
1126            $c =~ s@(?<=produced )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1127            $c =~ s@(?<=new size )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1128
1129         }
1130         $content = $c;
1131
1132     } elsif ($c =~ m/^(Tagger|Filter) ([^\s]*) has empty joblist. Nothing to do./) {
1133
1134         # Filter privoxy-filter-test has empty joblist. Nothing to do.
1135         # Tagger variable-test has empty joblist. Nothing to do.
1136
1137         $content =~ s@(?<=$1 )([^\s]*)@$h{'filter'}$1$h{'Standard'}@;
1138
1139     } elsif ($c =~ m/^De-chunking successful. Shrunk from (\d+) to (\d+)/) {
1140
1141         $req{$t}{'chunked-size'} = $1;
1142         $req{$t}{'dechunked-size'} = $2;
1143         $req{$t}{'dechunk-change'} = $req{$t}{'dechunked-size'} - $req{$t}{'chunked-size'};
1144
1145         $content .= " (" . h('Number') . $req{$t}{'dechunk-change'} . h('Standard') . ")";
1146
1147         $content =~ s@(?<=from )($req{$t}{'chunked-size'})@$h{'Number'}$1$h{'Standard'}@;
1148         $content =~ s@(?<=to )($req{$t}{'dechunked-size'})@$h{'Number'}$1$h{'Standard'}@;
1149
1150     } elsif ($c =~ m/^Decompression successful. Old size: (\d+), new size: (\d+)./) {
1151
1152         # Decompression successful. Old size: 670, new size: 1166.
1153
1154         $req{$t}{'size-compressed'} = $1;
1155         $req{$t}{'size-decompressed'} = $2;
1156         $req{$t}{'decompression-gain'} = $req{$t}{'size-decompressed'} - $req{$t}{'size-compressed'};
1157
1158         $content =~ s@(?<=Old size: )($req{$t}{'size-compressed'})@$h{'Number'}$1$h{'Standard'}@;
1159         $content =~ s@(?<=new size: )($req{$t}{'size-decompressed'})@$h{'Number'}$1$h{'Standard'}@;
1160
1161         # XXX: Create sub get_percentage()
1162         if ($req{$t}{'size-decompressed'}) {
1163             $req{$t}{'decompression-gain-percent'} =
1164                 $req{$t}{'decompression-gain'} / $req{$t}{'size-decompressed'} * 100;
1165
1166             $content .= " (saved: ";
1167             #$content .= h('Number') . $req{$t}{'decompression-gain'} . h('Standard');
1168             #$content .= "/";
1169             $content .= h('Number') . sprintf("%.2f%%", $req{$t}{'decompression-gain-percent'}) . h('Standard');
1170             $content .= ")";
1171         }
1172
1173     } elsif ($c =~ m/^(Need to de-chunk first)/) {
1174
1175         # Need to de-chunk first
1176         return '' if SUPPRESS_NEED_TO_DE_CHUNK_FIRST;
1177
1178     } elsif ($c =~ m/^(Adding (?:dynamic )?re_filter job)/) {
1179
1180         return ''  if (SUPPRESS_SUCCEEDED_FILTER_ADDITIONS && m/succeeded/);
1181
1182         # Adding re_filter job ...
1183         # Adding dynamic re_filter job s@^(?:\w*)\s+.*\s+HTTP/\d\.\d\s*@IP-ADDRESS: $origin@D\
1184         #  to filter client-ip-address succeeded.
1185
1186     } elsif ($c =~ m/^Reading in filter/) {
1187
1188         return '' unless SHOW_FILTER_READIN_IN;
1189
1190     } else {
1191
1192         found_unknown_content($content);
1193
1194     }
1195
1196     return $content;
1197 }
1198
1199 sub handle_loglevel_redirect ($) {
1200
1201     my $c = shift;
1202
1203     if ($c =~ m/^Decoding "([^""]*)"/) {
1204
1205          $req{$t}{'original-destination'} = $1;
1206          $c = highlight_matched_path($c, '(?<=Decoding ")[^"]*');
1207          $c =~ s@\"@@g;
1208
1209     } elsif ($c =~ m/^Checking/) {
1210
1211          # Checking /_ylt=A0geu.Z76BRGR9k/**http://search.yahoo.com/search?p=view+odb+presentation+on+freebsd\
1212          #  &ei=UTF-8&xargs=0&pstart=1&fr=moz2&b=11 for redirects.
1213
1214          # TODO: Change colour if really url-decoded
1215          $req{$t}{'decoded-original-destination'} = $1;
1216          $c = highlight_matched_path($c, '(?<=Checking ")[^"]*');
1217          $c =~ s@\"@@g;
1218
1219     } elsif ($c =~ m/^pcrs command "([^""]*)" changed /) {
1220
1221         # pcrs command "s@&from=rss@@" changed \
1222         #  "http://it.slashdot.org/article.pl?sid=07/03/02/1657247&from=rss"\
1223         #  to "http://it.slashdot.org/article.pl?sid=07/03/02/1657247" (1 hit).
1224         $c =~ s@(?<=pcrs command )"([^""]*)"@$h{'filter'}$1$h{'Standard'}@;
1225         $c = highlight_matched_url($c, '(?<=changed ")[^""]*');
1226         $c =~ s@(?<=changed )"([^""]*)"@$1@; # Remove quotes
1227         $c = highlight_matched_url($c, '(?<=to ")[^""]*');
1228         $c =~ s@(?<=to )"([^""]*)"@$1@; # Remove quotes
1229         $c =~ s@(\d+)(?= hits?)@$h{'hits'}$1$h{'Standard'}@;
1230
1231     } elsif ($c =~ m/^pcrs command "([^""]*)" didn\'t change/) {
1232
1233         # pcrs command "s@^http://([^.]+?)/?$@http://www.bing.com/search?q=$1@" didn't \
1234         #  change "http://www.example.org/".
1235         $c =~ s@(?<=pcrs command )"([^""]*)"@$h{'filter'}$1$h{'Standard'}@;
1236         $c = highlight_matched_url($c, '(?<=change ")[^""]*');
1237
1238     } elsif ($c =~ m/(^New URL is: )(.*)/) {
1239
1240         # New URL is: http://it.slashdot.org/article.pl?sid=07/03/04/1511210
1241         # XXX: Use URL highlighter
1242         # XXX: Save?
1243         $c = $1 . h('rewritten-URL') . $2 . h('Standard');
1244
1245     } elsif ($c =~ m/No pcrs command recognized, assuming that/) {
1246         # No pcrs command recognized, assuming that "http://config.privoxy.org/user-manual/favicon.png"\
1247         #  is already properly formatted.
1248         # XXX: assume the same?
1249         $c = highlight_matched_url($c, '(?<=assuming that \")[^"]*');
1250
1251     } else {
1252
1253         found_unknown_content($c);
1254
1255     }
1256
1257     return $c;
1258 }
1259
1260 sub handle_loglevel_gif_deanimate ($) {
1261
1262     my $content = shift;
1263
1264     if ($content =~ m/Success! GIF shrunk from (\d+) bytes to (\d+)\./) {
1265
1266         my $bytes_from = $1;
1267         my $bytes_to = $2;
1268         # Gif-Deanimate: Success! GIF shrunk from 205 bytes to 133.
1269         $content =~ s@$bytes_from@$h{'Number'}$bytes_from$h{'Standard'}@;
1270         # XXX: Do we need g in case of ($1 == $2)?
1271         $content =~ s@$bytes_to@$h{'Number'}$bytes_to$h{'Standard'}@;
1272
1273     } elsif ($content =~ m/GIF (not) changed/) {
1274
1275         # Gif-Deanimate: GIF not changed.
1276         return '' if SUPPRESS_GIF_NOT_CHANGED;
1277         $content =~ s@($1)@$h{'not'}$1$h{'Standard'}@;
1278
1279     } elsif ($content =~ m/^failed! \(gif parsing\)/) {
1280
1281         # failed! (gif parsing)
1282         # XXX: Replace this error message with something less stupid
1283         $content =~ s@(failed!)@$h{'error'}$1$h{'Standard'}@;
1284
1285     } elsif ($content =~ m/^Need to de-chunk first/) {
1286
1287         # Need to de-chunk first
1288         return '' if SUPPRESS_NEED_TO_DE_CHUNK_FIRST;
1289
1290     } elsif ($content =~ m/^(?:No GIF header found|failed while parsing)/) {
1291
1292         # No GIF header found (XXX: Did I ever commit this?)
1293         # failed while parsing 195 134747048 (XXX: never commited)
1294
1295         # Ignore these for now
1296
1297     } else {
1298
1299         found_unknown_content($content);
1300
1301     }
1302
1303     return $content;
1304 }
1305
1306 sub handle_loglevel_request ($) {
1307
1308     my $content = shift;
1309
1310     if ($content =~ m/crunch! /) {
1311
1312         # config.privoxy.org/send-stylesheet crunch! (CGI Call)
1313
1314         # Highlight crunch reasons
1315         foreach my $reason (keys %reason_colours) {
1316             $content =~ s@\(($reason)\)@$reason_colours{$reason}($1)$h{'Standard'}@g;
1317         }
1318         # Highlight request URL domain and ditch 'crunch!'
1319         $content = highlight_matched_pattern($content, 'request_', '[^ ]*(?= crunch!)');
1320         $content =~ s@ crunch!@@;
1321
1322     } elsif ($content =~ m/\[too long, truncated\]$/) {
1323
1324         # config.privoxy.org/edit-actions-submit?f=3&v=1176116716&s=7&Submit=Submit[...]&filter... [too long, truncated]
1325         $content = highlight_matched_pattern($content, 'request_', '^.*(?=\.\.\. \[too long, truncated\]$)');
1326
1327     } elsif ($content =~ m/(.*)/) { # XXX: Pretty stupid
1328
1329         # trac.vidalia-project.net/wiki/Volunteer?format=txt
1330         $content = h('request_') . $content . h('Standard');
1331
1332     } else {  # XXX: Nop
1333
1334         found_unknown_content($content);
1335
1336     }
1337
1338     return $content;
1339 }
1340
1341 sub handle_loglevel_crunch ($) {
1342
1343     my $content = shift;
1344
1345     # Highlight crunch reason
1346     foreach my $reason (keys %reason_colours) {
1347         $content =~ s@($reason)@$reason_colours{$reason}$1$h{'Standard'}@g;
1348     }
1349
1350     if ($content =~ m/\[too long, truncated\]$/) {
1351
1352         # Blocked: config.privoxy.org/edit-actions-submit?f=3&v=1176116716&s=7&Submit=Submit\
1353         #  [...]&filter... [too long, truncated]
1354         $content = highlight_matched_pattern($content, 'request_', '^.*(?=\.\.\. \[too long, truncated\]$)');
1355
1356     } else {
1357
1358         # Blocked: http://ads.example.org/
1359         $content = highlight_matched_pattern($content, 'request_', '(?<=: ).*');
1360     }
1361
1362     return $content;
1363 }
1364
1365 sub handle_loglevel_connect ($) {
1366
1367     my $c = shift;
1368
1369     if ($c =~ m/^via [^\s]+ to: [^\s]+/) {
1370
1371         # Connect: via 10.0.0.1:8123 to: www.example.org.noconnect
1372
1373         $c = highlight_matched_host($c, '(?<=via )[^\s]+');
1374         $c = highlight_matched_host($c, '(?<=to: )[^\s]+');
1375
1376     } elsif ($c =~ m/^connect to: .* failed: .*/) {
1377
1378         # connect to: www.example.org.noconnect failed: Operation not permitted
1379
1380         $c = highlight_matched_host($c, '(?<=connect to: )[^\s]+');
1381
1382         $c =~ s@(?<=failed: )(.*)@$h{'error'}$1$h{'Standard'}@;
1383
1384     } elsif ($c =~ m/^to ([^\s]*)( successful)?$/) {
1385
1386         # Connect: to www.nzherald.co.nz successful
1387         # Connect: to archiv.radiotux.de
1388
1389         return '' if SUPPRESS_SUCCESSFUL_CONNECTIONS;
1390         $c = highlight_matched_host($c, '(?<=to )[^\s]+');
1391
1392     } elsif ($c =~ m/^to ([^\s]*)$/) {
1393
1394         # Connect: to lists.sourceforge.net:443
1395
1396         $c = highlight_matched_host($c, '(?<=to )[^\s]+');
1397
1398     } elsif ($c =~ m/^accepted connection from .*/ or
1399              $c =~ m/^OK/) {
1400
1401         # accepted connection from 10.0.0.1
1402         # Privoxy 3.0.6 and earlier just say:
1403         # OK
1404         return '' if SUPPRESS_ACCEPTED_CONNECTIONS;
1405         $c = highlight_matched_host($c, '(?<=connection from ).*');
1406
1407     } elsif ($c =~ m/^write header to: .* failed:/) {
1408
1409         # write header to: 10.0.0.1 failed: Broken pipe
1410
1411         $c = highlight_matched_host($c, '(?<=write header to: )[^\s]*');
1412         $c =~ s@(?<=failed: )(.*)@$h{'Error'}$1$h{'Standard'}@;
1413
1414     } elsif ($c =~ m/^write header to client failed:/) {
1415
1416         # write header to client failed: Broken pipe
1417         # XXX: Stil in use?
1418         $c =~ s@(?<=failed: )(.*)@$h{'Error'}$1$h{'Standard'}@;
1419
1420     } elsif ($c =~ m/^socks4_connect:/) {
1421
1422         # socks4_connect: SOCKS request rejected or failed.
1423         $c =~ s@(?<=socks4_connect: )(.*)@$h{'Error'}$1$h{'Standard'}@;
1424
1425     } elsif ($c =~ m/^Listening for new connections/ or
1426              $c =~ m/^accept connection/) {
1427         # XXX: Highlight?
1428         # Privoxy versions above 3.0.6 say:
1429         # Listening for new connections ...
1430         # earlier versions say:
1431         # accept connection ...
1432         return '';
1433
1434     } elsif ($c =~ m/^accept failed:/) {
1435
1436         $c =~ s@(?<=accept failed: )(.*)@$h{'Error'}$1$h{'Standard'}@;
1437
1438     } elsif ($c =~ m/^Overriding forwarding settings/) {
1439
1440         # Overriding forwarding settings based on 'forward 10.0.0.1:8123'
1441         $c =~ s@(?<=based on \')(.*)(?=\')@$h{'configuration-line'}$1$h{'Standard'}@;
1442
1443     } elsif ($c =~ m/^Denying suspicious CONNECT request from/) {
1444
1445         # Denying suspicious CONNECT request from 10.0.0.1
1446         $c = highlight_matched_host($c, '(?<=from )[^\s]+'); # XXX: not an URL
1447
1448     } elsif ($c =~ m/^socks5_connect:/) {
1449
1450         $c =~ s@(?<=socks5_connect: )(.*)@$h{'error'}$1$h{'Standard'}@;
1451
1452     } elsif ($c =~ m/^Created new connection to/) {
1453
1454         # Created new connection to www.privoxy.org:80 on socket 11.
1455         $c = highlight_matched_host($c, '(?<=connection to )[^\s]+');
1456         $c =~ s@(?<=on socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1457
1458     } elsif ($c =~ m/^Found reusable socket/) {
1459
1460         # Found reusable socket 9 for www.privoxy.org:80 in slot 0.
1461         # 3.0.15 and later:
1462         # Found reusable socket 8 for www.privoxy.org:80 in slot 2.\
1463         #  Timestamp made 0 seconds ago. Timeout: 1. Latency: 0.
1464         $c =~ s@(?<=Found reusable socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1465         $c = highlight_matched_host($c, '(?<=for )[^\s]+');
1466         $c =~ s@(?<=in slot )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1467         $c =~ s@(?<=made )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1468         $c =~ s@(?<=Timeout: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1469         $c =~ s@(?<=Latency: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1470
1471     } elsif ($c =~ m/^Marking open socket/) {
1472
1473         # Marking open socket 9 for www.privoxy.org:80 in slot 0 as unused.
1474         $c =~ s@(?<=Marking open socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1475         $c = highlight_matched_host($c, '(?<=for )[^\s]+');
1476         $c =~ s@(?<=in slot )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1477
1478     } elsif ($c =~ m/^No reusable/) {
1479
1480         # No reusable socket for addons.mozilla.org:443 found. Opening a new one.
1481         $c = highlight_matched_host($c, '(?<=for )[^\s]+');
1482
1483     } elsif ($c =~ m/^(Remembering|Forgetting) socket/) {
1484
1485         # Remembering socket 13 for www.privoxy.org:80 in slot 0.
1486         # Forgetting socket 38 for www.privoxy.org:80 in slot 5.
1487
1488         $c =~ s@(?<=socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1489         $c = highlight_matched_host($c, '(?<=for )[^\s]+');
1490         $c =~ s@(?<=in slot )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1491
1492     } elsif ($c =~ m/^Socket/) {
1493
1494         # Socket 16 already forgotten or never remembered.
1495         $c =~ s@(?<=Socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1496
1497     } elsif ($c =~ m/^The connection to/) {
1498
1499         # The connection to www.privoxy.org:80 in slot 6 timed out. Closing socket 19. Timeout is: 61.
1500         # 3.0.15 and later:
1501         # The connection to 1.bp.blogspot.com:80 in slot 0 timed out. Closing socket 5.\
1502         #  Timeout is: 1. Assumed latency: 4.
1503         # The connection to 10.0.0.1:80 in slot 0 is no longer usable. Closing socket 4.
1504         $c = highlight_matched_host($c, '(?<=connection to )[^\s]+');
1505         $c =~ s@(?<=in slot )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1506         $c =~ s@(?<=Closing socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1507         $c =~ s@(?<=Timeout is: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1508         $c =~ s@(?<=Assumed latency: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1509
1510     } elsif ($c =~ m/^Stopped waiting for the request line./) {
1511
1512         # Stopped waiting for the request line. Timeout: 121.
1513         $c =~ s@(?<=Timeout: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1514
1515     } elsif ($c =~ m/^Waiting for \d/) {
1516
1517         # Waiting for 1 connections to timeout.
1518         $c =~ s@(?<=^Waiting for )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1519
1520     } elsif ($c =~ m/^Initialized/) {
1521
1522         # Initialized 20 socket slots.
1523         $c =~ s@(?<=Initialized )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1524
1525     } elsif ($c =~ m/^Done reading from server/) {
1526
1527         # Done reading from server. Expected content length: 24892. \
1528         #  Actual content length: 24892. Most recently received: 4412.
1529         # 3.0.15 and later:
1530         # Done reading from server. Expected content length: 24892. \
1531         #  Actual content length: 24892. Bytes most recently read: 4412.
1532         # Done reading from server. Content length: 6018 as expected. \
1533         #  Bytes most recently read: 294.
1534         $c =~ s@(?<=ontent length: )(\d+)@$h{'Number'}$1$h{'Standard'}@g;
1535         $c =~ s@(?<=received: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1536         $c =~ s@(?<=read: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1537
1538     } elsif ($c =~ m/^Continuing buffering headers/) {
1539
1540         # Continuing buffering headers. byte_count: 19. header_offset: 517. len: 536.
1541         $c =~ s@(?<=byte_count: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1542         $c =~ s@(?<=header_offset: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1543         $c =~ s@(?<=len: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1544         # 3.0.15 and later:
1545         # Continuing buffering headers. Bytes most recently read: %d.
1546         $c =~ s@(?<=read: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1547
1548     } elsif ($c =~ m/^Received \d+ bytes while/) {
1549
1550         # Received 206 bytes while expecting 12103.
1551         $c =~ s@(?<=Received )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1552         $c =~ s@(?<=expecting )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1553
1554     } elsif ($c =~ m/^(Rejecting c|C)onnection from/) {
1555
1556         # Connection from 81.163.28.218 dropped due to ACL
1557         # Rejecting connection from 178.63.152.227. Maximum number of connections reached.
1558         $c =~ s@(?<=onnection from )((?:\d+\.?){3}\d+)@$h{'Number'}$1$h{'Standard'}@;
1559
1560     } elsif ($c =~ m/^(?:Reusing|Closing) server socket \d./ or
1561              $c =~ m/^No additional client request/) {
1562
1563         # Reusing server socket 4. Opened for 10.0.0.1.
1564         # Closing server socket 2. Opened for 10.0.0.1.
1565         # No additional client request received in time. \
1566         #  Closing server socket 4, initially opened for 10.0.0.1.
1567         # No additional client request received in time on socket 29.
1568
1569         $c =~ s@(?<= socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1570         $c = highlight_matched_host($c, '(?<=for )[^\s]+(?=\.$)');
1571
1572     } elsif ($c =~ m/^Connected to /) {
1573
1574         # Connected to tor-jail[10.0.0.2]:9050.
1575
1576         $c = highlight_matched_host($c, '(?<=\[)[^\]]+');
1577         $c = highlight_matched_host($c, '(?<=Connected to )[^\[\s]+');
1578         $c =~ s@(?<=\]:)(\d+)@$h{'Number'}$1$h{'Standard'}@;
1579
1580     } elsif ($c =~ m/^Could not connect to /) {
1581
1582         # Could not connect to [10.0.0.1]:80.
1583
1584         $c = highlight_matched_host($c, '(?<=\[)[^\]]+');
1585         $c =~ s@(?<=\]:)(\d+)@$h{'Number'}$1$h{'Standard'}@;
1586
1587     } elsif ($c =~ m/^Waiting for the next client request/ or
1588              $c =~ m/^The connection on server socket/ or
1589              $c =~ m/^Client request arrived in time or the client closed the connection/) {
1590
1591         # Waiting for the next client request on socket 3. Keeping the server \
1592         #  socket 12 to a.fsdn.com open.
1593         # The connection on server socket 6 to upload.wikimedia.org isn't reusable. Closing.
1594         # Client request arrived in time or the client closed the connection on socket 12.
1595
1596         $c =~ s@(?<=on socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1597         $c =~ s@(?<=server socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1598         $c = highlight_matched_host($c, '(?<=to )[^\s]+');
1599
1600     } elsif ($c =~ m/^Marking the server socket/) {
1601
1602         # Marking the server socket 7 tainted.
1603
1604         $c =~ s@(?<=server socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1605
1606     } elsif ($c =~ m/^Reduced expected bytes to /) {
1607
1608         # Reduced expected bytes to 0 to account for the 1542 ones we already got.
1609         $c =~ s@(?<=bytes to )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1610         $c =~ s@(?<=for the )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1611
1612     } elsif ($c =~ m/^The client closed socket /) {
1613
1614         # The client closed socket 2 while the server socket 4 is still open.
1615         $c =~ s@(?<=closed socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1616         $c =~ s@(?<=server socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1617
1618     } elsif ($c =~ m/^Expected client content length set /) {
1619
1620         # Expected client content length set to 667325411 after reading 4999 bytes.
1621         $c =~ s@(?<=set to )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1622         $c =~ s@(?<=reading )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1623
1624     } elsif ($c =~ m/^Waiting for up to /) {
1625
1626         # Waiting for up to 4999 bytes from the client.
1627         $c =~ s@(?<=up to )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1628
1629     } elsif ($c =~ m/^Looks like we / or
1630              $c =~ m/^Unsetting keep-alive flag/ or
1631              $c =~ m/^No connections to wait/ or
1632              $c =~ m/^Complete client request received/ or
1633              $c =~ m/^Possible pipeline attempt detected./ or
1634              $c =~ m/^POST request detected. The connection will not be kept alive./ or
1635              $c =~ m/^The server still wants to talk, but the client hung up on us./ or
1636              $c =~ m/^The server didn't specify how long the connection will stay open/ or
1637              $c =~ m/^There might be a request body. The connection will not be kept alive/ or
1638              $c =~ m/^Stopping to watch the client socket. There's already another request waiting./ or
1639              $c =~ m/^Done reading from the client\.$/) {
1640
1641         # Looks like we reached the end of the last chunk. We better stop reading.
1642         # Looks like we read the end of the last chunk together with the server \
1643         #  headers. We better stop reading.
1644         # Looks like we got the last chunk together with the server headers. \
1645         #  We better stop reading.
1646         # Unsetting keep-alive flag.
1647         # No connections to wait for left.
1648         # Client request arrived in time or the client closed the connection.
1649         # Complete client request received
1650         # Possible pipeline attempt detected. The connection will not be \
1651         #  kept alive and we will only serve the first request.
1652         # POST request detected. The connection will not be kept alive.
1653         # The server still wants to talk, but the client hung up on us.
1654         # The server didn't specify how long the connection will stay open. Assume it's only a second.
1655         # There might be a request body. The connection will not be kept alive.
1656         # Stopping to watch the client socket. There's already another request waiting.
1657         # Done reading from the client\.
1658
1659     } else {
1660
1661         found_unknown_content($c);
1662
1663     }
1664
1665     return $c;
1666 }
1667
1668
1669 sub handle_loglevel_info ($) {
1670
1671     my $c = shift;
1672
1673     if ($c =~ m/^Rewrite detected:/) {
1674
1675         # Rewrite detected: GET http://10.0.0.2:88/blah.txt HTTP/1.1
1676         $c = highlight_matched_request_line($c, '(?<=^Rewrite detected: ).*');
1677
1678     } elsif ($c =~ m/^Decompress(ing deflated|ion didn)/ or
1679              $c =~ m/^Compressed content detected/ or
1680              $c =~ m/^Tagger/
1681             ) {
1682         # Decompressing deflated iob: 117
1683         # Decompression didn't result in any content.
1684         # Compressed content detected, content filtering disabled. Consider recompiling Privoxy\
1685         #  with zlib support or enable the prevent-compression action.
1686         # Tagger 'complete-url' created empty tag. Ignored.
1687
1688         # Ignored for now
1689
1690     } elsif ($c =~ m/^(Re)?loading configuration file /) {
1691
1692         # loading configuration file '/usr/local/etc/privoxy/config':
1693         # Reloading configuration file '/usr/local/etc/privoxy/config'
1694         $c =~ s@(?<=loading configuration file \')([^\']*)@$h{'file'}$1$h{'Standard'}@;
1695
1696     } elsif ($c =~ m/^Loading (actions|filter) file: /) {
1697
1698         # Loading actions file: /usr/local/etc/privoxy/default.action
1699         # Loading filter file: /usr/local/etc/privoxy/default.filter
1700         $c =~ s@(?<= file: )(.*)$@$h{'file'}$1$h{'Standard'}@;
1701
1702     } elsif ($c =~ m/^exiting by signal/) {
1703
1704         # exiting by signal 15 .. bye
1705         $c =~ s@(?<=exiting by signal )(\d+)@$h{'signal'}$1$h{'Standard'}@;
1706
1707     } elsif ($c =~ m/^Privoxy version/) {
1708
1709         # Privoxy version 3.0.7
1710         $c =~ s@(?<=^Privoxy version )(\d+\.\d+\.\d+)$@$h{'version'}$1$h{'Standard'}@;
1711
1712     } elsif ($c =~ m/^Program name: /) {
1713
1714         # Program name: /usr/local/sbin/privoxy
1715         $c =~ s@(?<=Program name: )(.*)@$h{'program-name'}$1$h{'Standard'}@;
1716
1717     } elsif ($c =~ m/^Listening on port /) {
1718
1719         # Listening on port 8118 on IP address 10.0.0.1
1720         $c =~ s@(?<=Listening on port )(\d+)@$h{'port'}$1$h{'Standard'}@;
1721         $c =~ s@(?<=on IP address )(.*)@$h{'ip-address'}$1$h{'Standard'}@;
1722
1723     } elsif ($c =~ m/^\(Re-\)Open(?:ing)? logfile/) {
1724
1725         # (Re-)Open logfile /var/log/privoxy/privoxy.log
1726         $c =~ s@(?<=Open logfile )(.*)@$h{'file'}$1$h{'Standard'}@;
1727
1728     } elsif ($c =~ m/^(Request from|Malformed server response detected)/) {
1729
1730         # Request from 10.0.0.1 denied. limit-connect{,} doesn't allow CONNECT requests to port 443.
1731         # Request from 10.0.0.1 marked for blocking. limit-connect{,} doesn't allow CONNECT requests to port 443.
1732         # Malformed server response detected. Downgrading to HTTP/1.0 impossible.
1733
1734         $c =~ s@(?<=Request from )([^\s]*)@$h{'ip-address'}$1$h{'Standard'}@;
1735         $c =~ s@(denied|blocking)@$h{'warning'}$1$h{'Standard'}@;
1736         $c =~ s@(CONNECT)@$h{'method'}$1$h{'Standard'}@;
1737         $c =~ s@(?<=to port )(\d+)@$h{'port'}$1$h{'Standard'}@;
1738
1739     } elsif ($c =~ m/^Status code/) {
1740
1741         # Status code 304 implies no body.
1742         $c =~ s@(?<=Status code )(\d+)@$h{'status-code'}$1$h{'Standard'}@;
1743
1744     } elsif ($c =~ m/^Method/) {
1745
1746         # Method HEAD implies no body.
1747         $c =~ s@(?<=Method )([^\s]+)@$h{'method'}$1$h{'Standard'}@;
1748
1749     } elsif ($c =~ m/^Buffer limit reached while extending /) {
1750
1751         # Buffer limit reached while extending the buffer (iob). Needed: 4197470. Limit: 4194304
1752         $c =~ s@(?<=Needed: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1753         $c =~ s@(?<=Limit: )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1754
1755     } elsif ($c =~ m/^No logfile configured/ or
1756              $c =~ m/^Malformerd HTTP headers detected and MS IIS5 hack enabled/ or
1757              $c =~ m/^Invalid \"chunked\" transfer/ or
1758              $c =~ m/^Support for/ or
1759              $c =~ m/^Flushing header and buffers/ or
1760              $c =~ m/^Can not resolve/
1761              ) {
1762
1763         # No logfile configured. Please enable it before reporting any problems.
1764         # Malformerd HTTP headers detected and MS IIS5 hack enabled. Expect an invalid \
1765         #  response or even no response at all.
1766         # No logfile configured. Logging disabled.
1767         # Invalid "chunked" transfer encoding detected and ignored.
1768         # Support for 'Connection: keep-alive' is experimental, incomplete and\
1769         #  known not to work properly in some situations.
1770         # Flushing header and buffers. Stepping back from filtering.
1771         # Can not resolve doesnotexist: hostname nor servname provided, or not known
1772
1773     } else {
1774
1775         found_unknown_content($c);
1776
1777     }
1778
1779     return $c;
1780 }
1781
1782 sub handle_loglevel_cgi ($) {
1783
1784     my $c = shift;
1785
1786     if ($c =~ m/^Granting access to/) {
1787
1788         #Granting access to http://config.privoxy.org/send-stylesheet, referrer http://p.p/ is trustworthy.
1789
1790     } elsif ($c =~ m/^Substituting: s(.)/) {
1791
1792         # Substituting: s/@else-not-FEATURE_ZLIB@.*@endif-FEATURE_ZLIB@//sigTU
1793         # XXX: prone to span several lines
1794
1795         my $delimiter = $1;
1796         #$c =~ s@(?<=failed: )(.*)@$h{'error'}$1$h{'Standard'}@;
1797         $c =~ s@(?!<=\\)($delimiter)@$h{'pcrs-delimiter'}$1$h{'Standard'}@g; # XXX: Too aggressive
1798         #$c =~ s@(?!<=\\)($1)@$h{'pcrs-delimiter'}$1$h{'Standard'}@g;
1799     }
1800
1801     return $c;
1802 }
1803
1804 sub handle_loglevel_force ($) {
1805
1806     my $c = shift;
1807
1808     if ($c =~ m/^Ignored force prefix in request:/) {
1809
1810         # Ignored force prefix in request: "GET http://10.0.0.1/PRIVOXY-FORCE/block HTTP/1.1"
1811         $c =~ s@^(Ignored)@$h{'ignored'}$1$h{'Standard'}@;
1812         $c = highlight_matched_request_line($c, '(?<=request: ")[^"]*');
1813
1814     } elsif ($c =~ m/^Enforcing request:/) {
1815
1816         # Enforcing request: "GET http://10.0.0.1/block HTTP/1.1".
1817         $c = highlight_matched_request_line($c, '(?<=request: ")[^"]*');
1818
1819     } else {
1820
1821         found_unknown_content($c);
1822
1823     }
1824
1825     return $c;
1826 }
1827
1828 sub handle_loglevel_error ($) {
1829
1830     my $c = shift;
1831
1832     if ($c =~ m/^Empty server or forwarder response received on socket \d+./) {
1833
1834         # Empty server or forwarder response received on socket 4.
1835         # Empty server or forwarder response received on socket 3. \
1836         #  Closing client socket 15 without sending data.
1837         $c =~ s@(?<=on socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1838         $c =~ s@(?<=client socket )(\d+)@$h{'Number'}$1$h{'Standard'}@;
1839     }
1840     # XXX: There are probably more messages that deserve highlighting.
1841
1842     return $c;
1843 }
1844
1845
1846 sub handle_loglevel_ignore ($) {
1847     return shift;
1848 }
1849
1850 sub gather_loglevel_request_stats ($$) {
1851     my $c = shift;
1852     my $thread = shift;
1853     our %stats;
1854
1855     $stats{requests}++;
1856 }
1857
1858 sub gather_loglevel_crunch_stats ($$) {
1859     my $c = shift;
1860     my $thread = shift;
1861     our %stats;
1862
1863     $stats{requests}++;
1864     $stats{crunches}++;
1865
1866     if ($c =~ m/^Redirected:/) {
1867         # Redirected: http://www.example.org/http://p.p/
1868         $stats{'fast-redirections'}++;
1869
1870     } elsif ($c =~ m/^Blocked:/) {
1871         # Blocked: blogger.googleusercontent.com:443
1872         $stats{'blocked'}++;
1873     }
1874 }
1875
1876
1877 sub gather_loglevel_error_stats ($$) {
1878
1879     my $c = shift;
1880     my $thread = shift;
1881     our %stats;
1882     our %thread_data;
1883
1884     if ($c =~ m/^Empty server or forwarder response received on socket \d+./) {
1885
1886         # Empty server or forwarder response received on socket 4.
1887         $stats{'empty-responses'}++;
1888         if ($thread_data{$thread}{'new_connection'}) {
1889             $stats{'empty-responses-on-new-connections'}++;
1890         } else {
1891             $stats{'empty-responses-on-reused-connections'}++;
1892         }
1893     }
1894 }
1895
1896 sub gather_loglevel_connect_stats ($$) {
1897
1898     my ($c, $thread) = @_;
1899     our %thread_data;
1900     our %stats;
1901
1902     if ($c =~ m/^via ([^\s]+) to: [^\s]+/) {
1903
1904         # Connect: via 10.0.0.1:8123 to: www.example.org.noconnect
1905         $thread_data{$thread}{'forwarder'} = $1; # XXX: is this missue?
1906
1907     } elsif ($c =~ m/^to ([^\s]*)$/) {
1908
1909         # Connect: to lists.sourceforge.net:443
1910
1911         $thread_data{$thread}{'forwarder'} = 'direct connection';
1912
1913     } elsif ($c =~ m/^Created new connection to/) {
1914
1915         # Created new connection to www.privoxy.org:80 on socket 11.
1916
1917         $thread_data{$thread}{'new_connection'} = 1;
1918
1919     } elsif ($c =~ m/^Reusing server socket \d./ or
1920              $c =~ m/^Found reusable socket/) {
1921
1922         # Reusing server socket 4. Opened for 10.0.0.1.
1923         # Found reusable socket 9 for www.privoxy.org:80 in slot 0.
1924
1925         $thread_data{$thread}{'new_connection'} = 0;
1926         $stats{'reused-connections'}++;
1927     }
1928 }
1929
1930 sub gather_loglevel_header_stats ($$) {
1931
1932     my ($c, $thread) = @_;
1933     our %stats;
1934
1935     if ($c =~ m/^A HTTP\/1\.1 response without/ or
1936         $c =~ m/^Keeping the server header 'Connection: keep-alive' around./)
1937     {
1938         # A HTTP/1.1 response without Connection header implies keep-alive.
1939         # Keeping the server header 'Connection: keep-alive' around.
1940         $stats{'server-keep-alive'}++;
1941
1942     } elsif ($c =~ m/^scan: ((\w+) (.+) (HTTP\/\d\.\d))/) {
1943
1944         # scan: HTTP/1.1 200 OK
1945         $stats{'method'}{$2}++;
1946         $stats{'ressource'}{$3}++;
1947         $stats{'http-version'}{$4}++;
1948
1949     } elsif ($c =~ m/^scan: Host: ([^\s]+)/) {
1950
1951         # scan: Host: p.p
1952         $stats{'hosts'}{$1}++;
1953     }
1954 }
1955
1956 sub init_stats () {
1957     our %stats = (
1958         requests => 0,
1959         crunches => 0,
1960         'server-keep-alive' => 0,
1961         'reused-connections' => 0,
1962         'empty-responses' => 0,
1963         'empty-responses-on-new-connections' => 0,
1964         'empty-responses-on-reused-connections' => 0,
1965         'fast-redirections' => 0,
1966         'blocked' => 0,
1967         'reused-connections' => 0,
1968         'server-keep-alive' => 0,
1969         );
1970 }
1971
1972 sub get_percentage ($$) {
1973     my $big = shift;
1974     my $small = shift;
1975     return "NaN" if ($big eq 0);
1976     return sprintf("%.2f%%", $small / $big * 100);
1977 }
1978
1979 sub print_stats () {
1980
1981     our %stats;
1982     our %cli_options;
1983     my $new_connections = $stats{requests} - $stats{crunches} - $stats{'reused-connections'};
1984     my $outgoing_requests = $stats{requests} - $stats{crunches};
1985
1986     if ($stats{requests} eq 0) {
1987         print "No requests yet.\n";
1988         return;
1989     }
1990
1991     print "Client requests total: " . $stats{requests} . "\n";
1992     print "Crunches: " . $stats{crunches} . " (" .
1993         get_percentage($stats{requests}, $stats{crunches}) . ")\n";
1994     print "Blocks: " . $stats{'blocked'} . " (" .
1995         get_percentage($stats{requests}, $stats{'blocked'}) . ")\n";
1996     print "Fast redirections: " . $stats{'fast-redirections'} . " (" .
1997         get_percentage($stats{requests}, $stats{'fast-redirections'}) . ")\n";
1998     print "Outgoing requests: " . $outgoing_requests . " (" .
1999         get_percentage($stats{requests}, $outgoing_requests) . ")\n";
2000     print "Server keep-alive offers: " . $stats{'server-keep-alive'} . " (" .
2001         get_percentage($stats{requests}, $stats{'server-keep-alive'}) . ")\n";
2002     print "New outgoing connections: " . $new_connections . " (" .
2003         get_percentage($stats{requests}, $new_connections) . ")\n";
2004     print "Reused connections: " . $stats{'reused-connections'} . " (" .
2005         get_percentage($stats{requests}, $stats{'reused-connections'}) .
2006         "; server offers accepted: " .
2007         get_percentage($stats{'server-keep-alive'}, $stats{'reused-connections'}) . ")\n";
2008     print "Empty responses: " . $stats{'empty-responses'} . " (" .
2009         get_percentage($stats{requests}, $stats{'empty-responses'}) . ")\n";
2010     print "Empty responses on new connections: "
2011          . $stats{'empty-responses-on-new-connections'} . " (" .
2012         get_percentage($stats{requests}, $stats{'empty-responses-on-new-connections'})
2013         . ")\n";
2014     print "Empty responses on reused connections: " .
2015         $stats{'empty-responses-on-reused-connections'} . " (" .
2016         get_percentage($stats{requests}, $stats{'empty-responses-on-reused-connections'}) .
2017         ")\n";
2018
2019     if ($stats{method} eq 0) {
2020         print "No response lines parsed yet yet.\n";
2021         return;
2022     }
2023     print "Method distribution:\n";
2024     foreach my $method (sort {$stats{'method'}{$b} <=> $stats{'method'}{$a}} keys %{$stats{'method'}}) {
2025         printf "%8d : %-8s\n", $stats{'method'}{$method}, $method;
2026     }
2027     print "Client HTTP versions:\n";
2028     foreach my $http_version (sort {$stats{'http-version'}{$b} <=> $stats{'http-version'}{$a}} keys %{$stats{'http-version'}}) {
2029         printf "%d : %s\n",  $stats{'http-version'}{$http_version}, $http_version;
2030     }
2031
2032     if ($cli_options{'url-statistics-threshold'} == 0) {
2033         print "URL statistics are disabled. Increase --url-statistics-threshold to enable them.\n";
2034     } else {
2035         print "Requested URLs:\n";
2036         foreach my $ressource (sort {$stats{'ressource'}{$b} <=> $stats{'ressource'}{$a}} keys %{$stats{'ressource'}}) {
2037             if ($stats{'ressource'}{$ressource} < $cli_options{'url-statistics-threshold'}) {
2038                 print "Skipped statistics for URLs below the treshold.\n";
2039                 last;
2040             }
2041             printf "%d : %s\n", $stats{'ressource'}{$ressource}, $ressource;
2042         }
2043     }
2044
2045     if ($cli_options{'host-statistics-threshold'} == 0) {
2046         print "Host statistics are disabled. Increase --host-statistics-threshold to enable them.\n";
2047     } else {
2048         print "Requested Hosts:\n";
2049         foreach my $host (sort {$stats{'hosts'}{$b} <=> $stats{'hosts'}{$a}} keys %{$stats{'hosts'}}) {
2050             if ($stats{'hosts'}{$host} < $cli_options{'host-statistics-threshold'}) {
2051                 print "Skipped statistics for Hosts below the treshold.\n";
2052                 last;
2053             }
2054             printf "%d : %s\n", $stats{'hosts'}{$host}, $host;
2055         }
2056     }
2057 }
2058
2059
2060 ################################################################################
2061 # Functions that actually print stuff
2062 ################################################################################
2063
2064 sub print_clf_message () {
2065
2066     our ($ip, $timestamp, $request_line, $status_code, $size);
2067     my $output = '';
2068
2069     return if DEBUG_SUPPRESS_LOG_MESSAGES;
2070
2071     # Rebuild highlighted
2072     $output .= $h{'Number'} . $ip . $h{'Standard'};
2073     $output .= " - - ";
2074     $output .= "[" . $h{'Timestamp'} . $timestamp . $h{'Standard'} . "]";
2075     $output .= " ";
2076     $output .= "\"" . highlight_request_line("$request_line") . "\"";
2077     $output .= " ";
2078     $output .= $h{'Status'} . $status_code . $h{'Standard'};
2079     $output .= " ";
2080     $output .= $h{'Number'} . $size . $h{'Standard'};
2081     $output .= $line_end;
2082
2083     print $output;
2084 }
2085
2086 sub print_non_clf_message ($) {
2087
2088     my $content = shift;
2089     my $msec_string = "." . $req{$t}{'msecs'} unless $no_msecs_mode;
2090     my $line_start = $html_output_mode ? '' : $h{"Standard"};
2091
2092     return if DEBUG_SUPPRESS_LOG_MESSAGES;
2093
2094     print $line_start
2095         . $time_colours[$time_colour_index % 2]
2096         . $req{$t}{'time-stamp'}
2097         . $msec_string
2098         . $h{Standard} . " "
2099         . $thread_colours{$t}
2100         . $t
2101         . $h{Standard}
2102         . " "
2103         . $h{$req{$t}{'log-level'}}
2104         . $req{$t}{'log-level'}
2105         . $h{Standard}
2106         . ": "
2107         . $content
2108         . $line_end;
2109 }
2110
2111 sub shorten_thread_id ($) {
2112
2113     my $thread_id = shift;
2114
2115     our %short_thread_ids;
2116     our $max_threadid;
2117
2118     unless (defined $short_thread_ids{$thread_id}) {
2119         $short_thread_ids{$thread_id} = sprintf "%.3d", $max_threadid++;
2120     }
2121
2122     return $short_thread_ids{$thread_id}
2123 }
2124
2125 sub parse_loop () {
2126
2127     my ($day, $time_stamp, $thread, $log_level, $content, $c, $msecs);
2128     my $last_msecs  = 0;
2129     my $last_thread = 0;
2130     my $last_timestamp = 0;
2131     my $filters_that_did_nothing;
2132     my $key;
2133     my $time_colour;
2134     $time_colour = paint_it('white');
2135
2136     my %log_level_handlers = (
2137         'Re-Filter'         => \&handle_loglevel_re_filter,
2138         'Header'            => \&handle_loglevel_header,
2139         'Connect'           => \&handle_loglevel_connect,
2140         'Redirect'          => \&handle_loglevel_redirect,
2141         'Request'           => \&handle_loglevel_request,
2142         'Crunch'            => \&handle_loglevel_crunch,
2143         'Gif-Deanimate'     => \&handle_loglevel_gif_deanimate,
2144         'Info'              => \&handle_loglevel_info,
2145         'CGI'               => \&handle_loglevel_cgi,
2146         'Force'             => \&handle_loglevel_force,
2147         'Error'             => \&handle_loglevel_error,
2148         'Fatal error'       => \&handle_loglevel_ignore,
2149         'Writing'           => \&handle_loglevel_ignore,
2150         'Received'          => \&handle_loglevel_ignore,
2151         'Unknown log level' => \&handle_loglevel_ignore,
2152     );
2153
2154     while (<>) {
2155
2156         if (m/^(\w{3} \d{2}) (\d\d:\d\d:\d\d)\.?(\d+)? (?:Privoxy\()?([^\)\s]*)[\)]? ([\w -]*): (.*?)\r?$/) {
2157             $thread = $t = ($shorten_thread_ids) ? shorten_thread_id($4) : $4;
2158             $req{$t}{'day'} = $day = $1;
2159             $req{$t}{'time-stamp'} = $time_stamp = $2;
2160             $req{$t}{'msecs'} = $msecs = $3 ? $3 : 0; # Only the cool kids have micro second resolution;
2161             $req{$t}{'log-level'} = $log_level = $5;
2162             $req{$t}{'content'} = $content = $c = $6;
2163             $req{$t}{'log-message'} = $_;
2164             $no_special_header_highlighting = 0;
2165
2166             if (defined($log_level_handlers{$log_level})) {
2167
2168                 $content = $log_level_handlers{$log_level}($content);
2169
2170             } else {
2171
2172                 die "No handler found for log level \"$log_level\"\n";
2173             }
2174
2175             # Highlight Truncations
2176             if (length($_) > 4000) {
2177                 $content =~ s@(too long, truncated)]$@$h{'Truncation'}$1$h{'Standard'}]@g;
2178             }
2179
2180             next unless $content;
2181
2182             # Register threads to keep the colour constant
2183             if (!defined($thread_colours{$thread})) {
2184                 $thread_colours{$thread} = $all_colours[$thread_colour_index % @all_colours];
2185                 $thread_colour_index++;
2186             }
2187
2188             # Switch timestamp colour if timestamps differ
2189             if (($msecs ne $last_msecs) || ($time_stamp ne $last_timestamp)) {
2190                debug_message("Tick tack!") if DEBUG_TICKS;
2191                $time_colour = $time_colours[$time_colour_index % 2];
2192                $time_colour_index++;
2193                $last_msecs = $msecs;
2194                $last_timestamp = $time_stamp;
2195             }
2196
2197             $last_thread = $thread;
2198
2199             print_non_clf_message($content);
2200
2201         } elsif (m/^((?:\d+\.\d+\.\d+\.\d+|[:\d]+)) - - \[(.*)\] "(.*)" (\d+) (\d+)/) {
2202
2203             # LOG_LEVEL_CLF lines look like this
2204             # 61.152.239.32 - - [04/Mar/2007:18:28:23 +0100] "GET \
2205             #  http://ad.yieldmanager.com/imp?z=1&Z=120x600&s=109339&u=http%3A%2F%2Fwww.365loan.co.uk%2F&r=1\
2206             #  HTTP/1.1" 403 1730
2207             our ($ip, $timestamp, $request_line, $status_code, $size) = ($1, $2, $3, $4, $5);
2208
2209             print_clf_message();
2210
2211         } else {
2212
2213             # Some Privoxy log messages span more than one line,
2214             # usually to dump lots of content that doesn't need any syntax highlighting.
2215             # XXX: add mechanism to forward these lines to the right handler anyway.
2216             chomp();
2217             unless (DEBUG_SUPPRESS_LOG_MESSAGES or (SUPPRESS_EMPTY_LINES and m/^\s+$/)) {
2218                 print and print get_line_end(); # unless (SUPPRESS_EMPTY_LINES and m/^\s+$/);
2219             }
2220         }
2221     }
2222 }
2223
2224 sub stats_loop () {
2225
2226     my ($day, $time_stamp, $msecs, $thread, $log_level, $content);
2227     my %log_level_handlers = (
2228          'Re-Filter'         => \&handle_loglevel_ignore,
2229          'Header'            => \&gather_loglevel_header_stats,
2230          'Connect'           => \&gather_loglevel_connect_stats,
2231          'Redirect'          => \&handle_loglevel_ignore,
2232          'Request'           => \&gather_loglevel_request_stats,
2233          'Crunch'            => \&gather_loglevel_crunch_stats,
2234          'Gif-Deanimate'     => \&handle_loglevel_ignore,
2235          'Info'              => \&handle_loglevel_ignore,
2236          'CGI'               => \&handle_loglevel_ignore,
2237          'Force'             => \&handle_loglevel_ignore,
2238          'Error'             => \&gather_loglevel_error_stats,
2239          'Fatal error'       => \&handle_loglevel_ignore,
2240          'Writing'           => \&handle_loglevel_ignore,
2241          'Received'          => \&handle_loglevel_ignore,
2242          'Unknown log level' => \&handle_loglevel_ignore
2243     );
2244
2245     while (<>) {
2246         if (m/^(\w{3} \d{2}) (\d\d:\d\d:\d\d)\.?(\d+)? (?:Privoxy\()?([^\)\s]*)[\)]? ([\w -]*): (.*?)\r?$/) {
2247             $day = $1;
2248             $time_stamp = $2;
2249             $msecs = $3 ? $3 : 0;
2250             $thread = $4;
2251             $log_level = $5;
2252             $content = $6;
2253
2254             if (defined($log_level_handlers{$log_level})) {
2255
2256                 $content = $log_level_handlers{$log_level}($content, $thread);
2257
2258             } else {
2259
2260                 die "No handler found for log level \"$log_level\"\n";
2261
2262             }
2263         }
2264     }
2265
2266     print_stats();
2267
2268 }
2269
2270 sub VersionMessage {
2271     my $version_message;
2272
2273     $version_message .= 'Privoxy-Log-Parser ' . PRIVOXY_LOG_PARSER_VERSION  . "\n";
2274     $version_message .= 'Copyright (C) 2007-2010 Fabian Keil <fk@fabiankeil.de>' . "\n";
2275     $version_message .= 'http://www.fabiankeil.de/sourcecode/privoxy-log-parser/' . "\n";
2276
2277     print $version_message;
2278 }
2279
2280 sub get_cli_options () {
2281
2282     our %cli_options = (
2283         'html-output'              => CLI_OPTION_DEFAULT_TO_HTML_OUTPUT,
2284         'title'                    => CLI_OPTION_TITLE,
2285         'no-syntax-highlighting'   => CLI_OPTION_NO_SYNTAX_HIGHLIGHTING,
2286         'no-embedded-css'          => CLI_OPTION_NO_EMBEDDED_CSS,
2287         'no-msecs'                 => CLI_OPTION_NO_MSECS,
2288         'shorten-thread-ids'       => CLI_OPTION_SHORTEN_THREAD_IDS,
2289         'show-ineffective-filters' => CLI_OPTION_SHOW_INEFFECTIVE_FILTERS,
2290         'accept-unknown-messages'  => CLI_OPTION_ACCEPT_UNKNOWN_MESSAGES,
2291         'statistics'               => CLI_OPTION_STATISTICS,
2292         'url-statistics-threshold' => CLI_OPTION_URL_STATISTICS_THRESHOLD,
2293         'host-statistics-threshold'=> CLI_OPTION_HOST_STATISTICS_THRESHOLD,
2294     );
2295
2296     GetOptions (
2297         'html-output'              => \$cli_options{'html-output'},
2298         'title'                    => \$cli_options{'title'},
2299         'no-syntax-highlighting'   => \$cli_options{'no-syntax-highlighting'},
2300         'no-embedded-css'          => \$cli_options{'no-embedded-css'},
2301         'no-msecs'                 => \$cli_options{'no-msecs'},
2302         'shorten-thread-ids'       => \$cli_options{'shorten-thread-ids'},
2303         'show-ineffective-filters' => \$cli_options{'show-ineffective-filters'},
2304         'accept-unknown-messages'  => \$cli_options{'accept-unknown-messages'},
2305         'statistics'               => \$cli_options{'statistics'},
2306         'url-statistics-threshold=s'=> \$cli_options{'url-statistics-threshold'},
2307         'host-statistics-threshold=s'=> \$cli_options{'host-statistics-threshold'},
2308         'version'                  => sub { VersionMessage && exit(0) },
2309         'help'                     => \&help,
2310    ) or exit(1);
2311
2312    $html_output_mode = cli_option_is_set('html-output');
2313    $no_msecs_mode = cli_option_is_set('no-msecs');
2314    $shorten_thread_ids = cli_option_is_set('shorten-thread-ids');
2315    $line_end = get_line_end();
2316 }
2317
2318 sub help () {
2319
2320     our %cli_options;
2321
2322     VersionMessage();
2323
2324     print << "    EOF"
2325
2326 Options and their default values if they have any:
2327     [--accept-unknown-messages]
2328     [--host-statistics-threshold $cli_options{'host-statistics-threshold'}]
2329     [--html-output]
2330     [--no-embedded-css]
2331     [--no-msecs]
2332     [--no-syntax-highlighting]
2333     [--shorten-thread-ids]
2334     [--show-ineffective-filters]
2335     [--statistics]
2336     [--url-statistics-threshold $cli_options{'url-statistics-threshold'}]
2337     [--title $cli_options{'title'}]
2338     [--version]
2339 see "perldoc $0" for more information
2340     EOF
2341     ;
2342     exit(0);
2343 }
2344
2345 ################################################################################
2346 # main
2347 ################################################################################
2348 sub main () {
2349
2350     get_cli_options();
2351     set_background(DEFAULT_BACKGROUND);
2352     prepare_our_stuff();
2353
2354     print_intro();
2355
2356     if (cli_option_is_set('statistics')) {
2357         stats_loop();
2358     } else {
2359         parse_loop();
2360     }
2361
2362     print_outro();
2363 }
2364
2365 main();
2366
2367 =head1 NAME
2368
2369 B<privoxy-log-parser> - A parser and syntax-highlighter for Privoxy log messages
2370
2371 =head1 SYNOPSIS
2372
2373 B<privoxy-log-parser> [B<--accept-unknown-messages>] [B<--html-output>]
2374 [B<--no-msecs>] [B<--no-syntax-higlighting>] [B<--statistics>]
2375 [B<--shorten-thread-ids>] [B<--show-ineffective-filters>]
2376 [B<--url-statistics-threshold>] [B<--version>]
2377
2378 =head1 DESCRIPTION
2379
2380 B<privoxy-log-parser> reads Privoxy log messages and
2381
2382 - syntax-highlights recognized lines,
2383
2384 - reformats some of them for easier comprehension,
2385
2386 - filters out less useful messages, and
2387
2388 - (in some cases) calculates additional information,
2389   like the compression ratio or how a filter affected
2390   the content size.
2391
2392 With B<privoxy-log-parser> you should be able to increase Privoxy's log level
2393 without getting confused by the resulting amount of output. For example for
2394 "debug 64" B<privoxy-log-parser> will (by default) only show messages that
2395 affect the content. If a filter doesn't cause any hits, B<privoxy-log-parser>
2396 will hide the "filter foo caused 0 hits" message.
2397
2398 =head1 OPTIONS
2399
2400 [B<--accept-unknown-messages>] Don't print warnings in case of unknown messages,
2401 just don't highlight them.
2402
2403 [B<--host-statistics-threshold>] Only show the request count for a host
2404 if it's above or equal to the given threshold. If the threshold is 0, host
2405 statistics are disabled.
2406
2407 [B<--html-output>] Use HTML and CSS for the syntax highlighting. If this option is
2408 omitted, ANSI escape sequences are used unless B<--no-syntax-highlighting> is active.
2409 This option is only intended to make embedding log excerpts in web pages easier.
2410 It does not escape any input!
2411
2412 [B<--no-msecs>] Don't expect milisecond resolution
2413
2414 [B<--no-syntax-highlighting>] Disable syntax-highlighting. Useful when
2415 the filtered output is piped into less in which case the ANSI control
2416 codes don't work, or if the terminal itself doesn't support the control
2417 codes.
2418
2419 [B<--shorten-thread-ids>] Shorten the thread ids to a three-digit decimal number.
2420 Note that the mapping from thread ids to shortened ids is created at run-time
2421 and thus varies with the input.
2422
2423 [B<--show-ineffective-filters>] Don't suppress log lines for filters
2424 that didn't modify the content.
2425
2426 [B<--statistics>] Gather various statistics instead of syntax highlighting
2427 log messages. This is an experimental feature, if the results look wrong
2428 they very well might be. Also note that the results are pretty much guaranteed
2429 to be incorrect if Privoxy and Privoxy-Log-Parser aren't in sync.
2430
2431 [B<--url-statistics-threshold>] Only show the request count for a ressource
2432 if it's above or equal to the given threshold. If the threshold is 0, URL
2433 statistics are disabled.
2434
2435 [B<--version>] Print version and exit.
2436
2437 =head1 EXAMPLES
2438
2439 To monitor a log file:
2440
2441 tail -F /usr/jails/privoxy-jail/var/log/privoxy/privoxy.log | B<privoxy-log-parser>
2442
2443 Replace '-F' with '-f' if your tail implementation lacks '-F' support
2444 or if the log won't get rotated anyway. The log file location depends
2445 on your system (Doh!).
2446
2447 To monitor Privoxy without having it write to a log file:
2448
2449 privoxy --no-daemon /usr/jails/privoxy-jail/usr/local/etc/privoxy/config 2>&1 | B<privoxy-log-parser>
2450
2451 Again, the config file location depends on your system. Output redirection
2452 depends on your shell, the above works with bourne shells.
2453
2454 To read a processed Privoxy log file from top to bottom, letting the content
2455 scroll by slightly faster than you can read:
2456
2457 B<privoxy-log-parser> < /usr/jails/privoxy-jail/var/log/privoxy/privoxy.log
2458
2459 This is probably only useful to fill screens in the background of haxor movies.
2460
2461 =head1 CAVEATS
2462
2463 Syntax highlighting with ANSI escape sequences will look strange
2464 if your background color isn't black.
2465
2466 Some messages aren't recognized yet and will not be fully highlighted.
2467
2468 B<privoxy-log-parser> is developed with Privoxy 3.0.7 or later in mind,
2469 using earlier Privoxy versions will probably result in an increased amount
2470 of unrecognized log lines.
2471
2472 Privoxy's log files tend to be rather large. If you use HTML
2473 highlighting some browsers can't handle them, get confused and
2474 will eventually crash because of segmentation faults or unexpected
2475 exceptions. This is a problem in the browser and not B<privoxy-log-parser>'s
2476 fault.
2477
2478 =head1 BUGS
2479
2480 Many settings can't be controlled through command line options yet.
2481
2482 =head1 SEE ALSO
2483
2484 privoxy(1)
2485
2486 =head1 AUTHOR
2487
2488 Fabian Keil <fk@fabiankeil.de>
2489
2490 =cut