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