Bail out if a configuration file starts with a byte order mark
[exim.git] / src / src / exigrep.src
CommitLineData
8c4f17b3 1#! PERL_COMMAND
059ec3d9 2
8c4f17b3 3use warnings;
059ec3d9 4use strict;
4d3d955f 5BEGIN { pop @INC if $INC[-1] eq '.' };
059ec3d9 6
0a27a822
HSHR
7use Pod::Usage;
8use Getopt::Long;
9
3386088d 10# Copyright (c) 2007-2015 University of Cambridge.
059ec3d9
PH
11# See the file NOTICE for conditions of use and distribution.
12
13# Except when they appear in comments, the following placeholders in this
14# source are replaced when it is turned into a runnable script:
15#
16# PERL_COMMAND
17# ZCAT_COMMAND
18# COMPRESS_SUFFIX
19
20# PROCESSED_FLAG
21
22# This is a perl script which extracts from an Exim log all entries
23# for all messages that have an entry that matches a given pattern.
24# If *any* entry for a particular message matches the pattern, *all*
25# entries for that message are displayed.
26
27# We buffer up information on a per-message basis. It is done this way rather
28# than reading the input twice so that the input can be a pipe.
29
30# There must be one argument, which is the pattern. Subsequent arguments
31# are the files to scan; if none, the standard input is read. If any file
32# appears to be compressed, it is passed through zcat. We can't just do this
33# for all files, because zcat chokes on non-compressed files.
34
75b1493f
PH
35# Performance optimized in 02/02/2007 by Jori Hamalainen
36# Typical run time acceleration: 4 times
37
38
059ec3d9
PH
39use POSIX qw(mktime);
40
41
42# This subroutine converts a time/date string from an Exim log line into
43# the number of seconds since the epoch. It handles optional timezone
44# information.
45
46sub seconds {
47my($year,$month,$day,$hour,$min,$sec,$tzs,$tzh,$tzm) =
75b1493f 48 $_[0] =~ /^(\d{4})-(\d\d)-(\d\d)\s(\d\d):(\d\d):(\d\d)(?>\s([+-])(\d\d)(\d\d))?/o;
059ec3d9
PH
49
50my $seconds = mktime $sec, $min, $hour, $day, $month - 1, $year - 1900;
51
52if (defined $tzs)
53 {
54 $seconds -= $tzh * 3600 + $tzm * 60 if $tzs eq "+";
55 $seconds += $tzh * 3600 + $tzm * 60 if $tzs eq "-";
56 }
57
58return $seconds;
59}
60
61
62# This subroutine processes a single line (in $_) from a log file. Program
63# defensively against short lines finding their way into the log.
64
0a27a822
HSHR
65my (%saved, %id_list, $pattern);
66
67my $queue_time = -1;
68my $insensitive = 1;
69my $invert = 0;
70my $related = 0;
71my $use_pager = 1;
72my $literal = 0;
73
059ec3d9 74
0eb51736 75# If using "related" option, have to track extra message IDs
0eb51736
TL
76my $related_re='';
77my @Mids = ();
78
059ec3d9 79sub do_line {
395ff96d
PH
80
81# Convert syslog lines to mainlog format, as in eximstats.
82
75b1493f 83if (!/^\d{4}-/o) { $_ =~ s/^.*? exim\b.*?: //o; }
395ff96d 84
059ec3d9 85return unless
c0997ccb 86 my($date,$id) = /^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d (?:[+-]\d{4} )?)(?:\[\d+\] )?(\w{6}\-\w{6}\-\w{2})?/o;
059ec3d9
PH
87
88# Handle the case when the log line belongs to a specific message. We save
89# lines for specific messages until the message is complete. Then either print
f3f065bb 90# or discard.
059ec3d9 91
75b1493f 92if (defined $id)
059ec3d9
PH
93 {
94 $saved{$id} = '' unless defined($saved{$id});
95
96 # Save up the data for this message in case it becomes interesting later.
97
98 $saved{$id} .= $_;
99
75b1493f 100 # Are we interested in this id ? Short circuit if we already were interested.
059ec3d9 101
b2d5182b
PH
102 if ($invert)
103 {
104 $id_list{$id} = 1 if (!defined($id_list{$id}));
105 $id_list{$id} = 0 if (($insensitive && /$pattern/io) || /$pattern/o);
106 }
107 else
108 {
0eb51736
TL
109 if (defined $id_list{$id} ||
110 ($insensitive && /$pattern/io) || /$pattern/o)
111 {
112 $id_list{$id} = 1;
113 get_related_ids($id) if $related;
114 }
115 elsif ($related && $related_re)
116 {
117 grep_for_related($_, $id);
118 }
b2d5182b 119 }
059ec3d9
PH
120
121 # See if this is a completion for some message. If it is interesting,
122 # print it, but in any event, throw away what was saved.
123
75b1493f 124 if (index($_, 'Completed') != -1 ||
3ce62588
PH
125 index($_, 'SMTP data timeout') != -1 ||
126 (index($_, 'rejected') != -1 &&
127 /^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d (?:[+-]\d{4} )?)(?:\[\d+\] )?\w{6}\-\w{6}\-\w{2} rejected/o))
059ec3d9 128 {
75b1493f
PH
129 if ($queue_time != -1 &&
130 $saved{$id} =~ /^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d ([+-]\d{4} )?)/o)
059ec3d9
PH
131 {
132 my $old_sec = &seconds($1);
133 my $sec = &seconds($date);
3ce62588 134 $id_list{$id} = 0 if $id_list{$id} && $sec - $old_sec <= $queue_time;
059ec3d9
PH
135 }
136
3ce62588 137 print "$saved{$id}\n" if ($id_list{$id});
b2d5182b 138 delete $id_list{$id};
059ec3d9
PH
139 delete $saved{$id};
140 }
141 }
142
143# Handle the case where the log line does not belong to a specific message.
144# Print it if it is interesting.
145
b2d5182b
PH
146elsif ( ($invert && (($insensitive && !/$pattern/io) || !/$pattern/o)) ||
147 (!$invert && (($insensitive && /$pattern/io) || /$pattern/o)) )
75b1493f 148 { print "$_\n"; }
059ec3d9
PH
149}
150
89b68021
TL
151# Rotated log files are frequently compressed and there are a variety of
152# formats it could be compressed with. Rather than use just one that is
153# detected and hardcoded at Exim compile time, detect and use what the
154# logfile is compressed with on the fly.
155#
156# List of known compression extensions and their associated commands:
157my $compressors = {
158 gz => { cmd => 'zcat', args => '' },
159 bz2 => { cmd => 'bzcat', args => '' },
160 xz => { cmd => 'xzcat', args => '' },
161 lzma => { cmd => 'lzma', args => '-dc' }
162};
163my $csearch = 0;
164
165sub detect_compressor_bin
166 {
167 my $ext = shift();
168 my $c = $compressors->{$ext}->{cmd};
169 $compressors->{$ext}->{bin} = `which $c 2>/dev/null`;
170 chomp($compressors->{$ext}->{bin});
171 }
172
173sub detect_compressor_capable
174 {
175 my $filename = shift();
176 map { &detect_compressor_bin($_) } keys %$compressors
177 if (!$csearch);
178 $csearch = 1;
179 return undef
180 unless (grep {$filename =~ /\.(?:$_)$/} keys %$compressors);
181 # Loop through them, figure out which one it detected,
182 # and build the commandline.
183 my $cmdline = undef;
184 foreach my $ext (keys %$compressors)
185 {
186 if ($filename =~ /\.(?:$ext)$/)
187 {
4c04137d 188 # Just die if compressor not found; if this occurs in the middle of
89b68021
TL
189 # two valid files with a lot of matches, error could easily be missed.
190 die("Didn't find $ext decompressor for $filename\n")
191 if ($compressors->{$ext}->{bin} eq '');
192 $cmdline = $compressors->{$ext}->{bin} ." ".
193 $compressors->{$ext}->{args};
194 last;
195 }
196 }
197 return $cmdline;
198 }
059ec3d9 199
0eb51736
TL
200sub grep_for_related {
201 my ($line,$id) = @_;
202 $id_list{$id} = 1 if $line =~ m/$related_re/;
203}
204
205sub get_related_ids {
206 my ($id) = @_;
207 push @Mids, $id unless grep /\b$id\b/, @Mids;
208 my $re = join '|', @Mids;
209 $related_re = qr/$re/;
210}
211
059ec3d9
PH
212# The main program. Extract the pattern and make sure any relevant characters
213# are quoted if the -l flag is given. The -t flag gives a time-on-queue value
0eb51736
TL
214# which is an additional condition. The -M flag will also display "related"
215# loglines (msgid from matched lines is searched in following lines).
059ec3d9 216
0a27a822
HSHR
217GetOptions(
218 'I|sensitive' => sub { $insensitive = 0 },
219 'l|literal' => \$literal,
220 'M|related' => \$related,
221 't|queue-time=i' => \$queue_time,
222 'pager!' => \$use_pager,
223 'v|invert' => \$invert,
224 'h|help' => sub { pod2usage(-exit => 0, -verbose => 1) },
225 'm|man' => sub {
226 pod2usage(
227 -exit => 0,
228 -verbose => 2,
229 -noperldoc => system('perldoc -V 2>/dev/null >&2')
230 );
231 },
232) and @ARGV or pod2usage;
059ec3d9
PH
233
234$pattern = shift @ARGV;
0a27a822 235$pattern = quotemeta $pattern if $literal;
059ec3d9 236
ab13201f 237# Start a pager if output goes to a terminal
0a27a822 238if (-t 1 and $use_pager)
ab13201f
HSHR
239 {
240 foreach ($ENV{PAGER}//(), 'less', 'more')
241 {
242 open(my $pager, '|-', $_) or next;
243 select $pager;
244 last;
245 }
246}
059ec3d9
PH
247
248# If file arguments are given, open each one and process according as it is
249# is compressed or not.
250
251if (@ARGV)
252 {
253 foreach (@ARGV)
254 {
255 my $filename = $_;
fd4c285c 256 if (-x 'ZCAT_COMMAND' && $filename =~ /\.(?:COMPRESS_SUFFIX)$/o)
059ec3d9
PH
257 {
258 open(LOG, "ZCAT_COMMAND $filename |") ||
259 die "Unable to zcat $filename: $!\n";
260 }
89b68021
TL
261 elsif (my $cmdline = &detect_compressor_capable($filename))
262 {
263 open(LOG, "$cmdline $filename |") ||
264 die "Unable to decompress $filename: $!\n";
265 }
059ec3d9
PH
266 else
267 {
268 open(LOG, "<$filename") || die "Unable to open $filename: $!\n";
269 }
270 do_line() while (<LOG>);
271 close(LOG);
272 }
273 }
274
275# If no files are named, process STDIN only
276
277else { do_line() while (<STDIN>); }
278
3ce62588 279# At the end of processing all the input, print any uncompleted messages.
059ec3d9 280
79749a79
PH
281for (keys %id_list)
282 {
3ce62588 283 print "+++ $_ has not completed +++\n$saved{$_}\n";
79749a79 284 }
059ec3d9 285
e236f915
HSHR
286__END__
287
288=head1 NAME
289
290exigrep - search Exim's main log
291
292=head1 SYNOPSIS
293
294B<exigrep> [options] pattern [log] ...
295
296=head1 DESCRIPTION
297
298The B<exigrep> utility is a Perl script that searches one or more main log
299files for entries that match a given pattern. When it finds a match,
300it extracts all the log entries for the relevant message, not just
301those that match the pattern. Thus, B<exigrep> can extract complete log
302entries for a given message, or all mail for a given user, or for a
303given host, for example.
304
305If no file names are given on the command line, the standard input is read.
306
307For known file extensions indicating compression (F<.gz>, F<.bz2>, F<.xz>, and F<.lzma>)
308a suitable de-compressor is used, if available.
309
0a27a822
HSHR
310The output is sent through a pager if a terminal is connected to STDOUT. As
311pager are considered: C<$ENV{PAGER}>, C<less>, C<more>.
312
e236f915
HSHR
313=head1 OPTIONS
314
315=over
316
0a27a822 317=item B<-l>|B<--literal>
e236f915
HSHR
318
319This means 'literal', that is, treat all characters in the
320pattern as standing for themselves. Otherwise the pattern must be a
321Perl regular expression. The pattern match is case-insensitive.
322
0a27a822 323=item B<-t>|B<--queue-time> I<seconds>
e236f915
HSHR
324
325Limit the output to messages that spent at least I<seconds> in the
326queue.
327
0a27a822 328=item B<-I>|B<--sensitive>
e236f915
HSHR
329
330Do a case sensitive search.
331
0a27a822 332=item B<-v>|B<--invert>
e236f915
HSHR
333
334Invert the meaning of the search pattern. That is, print message log
335entries that are not related to that pattern.
336
0a27a822 337=item B<-M>|B<--related>
e236f915
HSHR
338
339Search for related messages too.
340
0a27a822
HSHR
341=item B<--no-pager>
342
343Do not use a pager, even if STDOUT is connected to a terminal.
344
345=item B<-h>|B<--help>
e236f915
HSHR
346
347Print a short reference help. For more detailed help try L<exigrep(8)>,
348or C<exigrep -m>.
349
0a27a822 350=item B<-m>|B<--man>
e236f915
HSHR
351
352Print this manual page of B<exigrep>.
353
354=back
355
356=head1 SEE ALSO
357
358L<exim(8)>, L<perlre(1)>, L<Exim|http://exim.org/>
359
360=head1 AUTHOR
361
362This manual page was stitched together from spec.txt by Andreas Metzler L<ametzler at downhill.at.eu.org>
363and updated by Heiko Schlittermann L<hs@schlittermann.de>.
364
365=cut