3 # Copyright (c) The Exim Maintainers 2020 - 2023
4 # Copyright (c) 2007-2017 University of Cambridge.
5 # See the file NOTICE for conditions of use and distribution.
6 # SPDX-License-Identifier: GPL-2.0-or-later
10 BEGIN { pop @INC if $INC[-1] eq '.' };
13 use Getopt::Long qw(:config no_ignore_case);
16 # Except when they appear in comments, the following placeholders in this
17 # source are replaced when it is turned into a runnable script:
25 # This is a perl script which extracts from an Exim log all entries
26 # for all messages that have an entry that matches a given pattern.
27 # If *any* entry for a particular message matches the pattern, *all*
28 # entries for that message are displayed.
30 # We buffer up information on a per-message basis. It is done this way rather
31 # than reading the input twice so that the input can be a pipe.
33 # There must be one argument, which is the pattern. Subsequent arguments
34 # are the files to scan; if none, the standard input is read. If any file
35 # appears to be compressed, it is passed through zcat. We can't just do this
36 # for all files, because zcat chokes on non-compressed files.
38 # Performance optimized in 02/02/2007 by Jori Hamalainen
39 # Typical run time acceleration: 4 times
45 # This subroutine converts a time/date string from an Exim log line into
46 # the number of seconds since the epoch. It handles optional timezone
51 my($year,$month,$day,$hour,$min,$sec,$tzs,$tzh,$tzm) =
52 $_[0] =~ /^(\d{4})-(\d\d)-(\d\d)\s(\d\d):(\d\d):(\d\d)(?:.\d+)?(?>\s([+-])(\d\d)(\d\d))?/o;
54 my $seconds = mktime $sec, $min, $hour, $day, $month - 1, $year - 1900;
58 $seconds -= $tzh * 3600 + $tzm * 60 if $tzs eq "+";
59 $seconds += $tzh * 3600 + $tzm * 60 if $tzs eq "-";
66 # This subroutine processes a single line (in $_) from a log file. Program
67 # defensively against short lines finding their way into the log.
69 my (%saved, %id_list, $pattern);
79 # If using "related" option, have to track extra message IDs
86 # Convert syslog lines to mainlog format, as in eximstats.
88 if (!/^\d{4}-/o) { $_ =~ s/^.*? exim\b.*?: //o; }
91 my($date,$id) = /^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d(?:\.\d+)? (?:[+-]\d{4} )?)(?:\[\d+\] )?(\w{6}\-\w{6}\-\w{2}|\w{6}-\w{11}-\w{4})?/o;
93 # Handle the case when the log line belongs to a specific message. We save
94 # lines for specific messages until the message is complete. Then either print
99 $saved{$id} = '' unless defined($saved{$id});
101 # Save up the data for this message in case it becomes interesting later.
105 # Are we interested in this id ? Short circuit if we already were interested.
109 $id_list{$id} = 1 if (!defined($id_list{$id}));
110 $id_list{$id} = 0 if (($insensitive && /$pattern/io) || /$pattern/o);
114 if (defined $id_list{$id} ||
115 ($insensitive && /$pattern/io) || /$pattern/o)
118 get_related_ids($id) if $related;
120 elsif ($related && $related_re)
122 grep_for_related($_, $id);
126 # See if this is a completion for some message. If it is interesting,
127 # print it, but in any event, throw away what was saved.
129 if (index($_, 'Completed') != -1 ||
130 index($_, 'SMTP data timeout') != -1 ||
131 (index($_, 'rejected') != -1 &&
132 /^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d(?:\.\d+)? (?:[+-]\d{4} )?)(?:\[\d+\] )?(?:\w{6}\-\w{6}\-\w{2}|\w{6}-\w{11}-\w{4}) rejected/o))
134 if ($queue_time != -1 &&
135 $saved{$id} =~ /^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d ([+-]\d{4} )?)/o)
137 my $old_sec = &seconds($1);
138 my $sec = &seconds($date);
139 $id_list{$id} = 0 if $id_list{$id} && $sec - $old_sec <= $queue_time;
142 print "$saved{$id}\n" if ($id_list{$id});
143 delete $id_list{$id};
148 # Handle the case where the log line does not belong to a specific message.
149 # Print it if it is interesting.
151 elsif ( ($invert && (($insensitive && !/$pattern/io) || !/$pattern/o)) ||
152 (!$invert && (($insensitive && /$pattern/io) || /$pattern/o)) )
156 # Rotated log files are frequently compressed and there are a variety of
157 # formats it could be compressed with. Rather than use just one that is
158 # detected and hardcoded at Exim compile time, detect and use what the
159 # logfile is compressed with on the fly.
161 # List of known compression extensions and their associated commands:
163 gz => { cmd => 'zcat', args => '' },
164 bz2 => { cmd => 'bzcat', args => '' },
165 xz => { cmd => 'xzcat', args => '' },
166 lzma => { cmd => 'lzma', args => '-dc' },
167 zst => { cmd => 'zstdcat', args => '' },
171 sub detect_compressor_bin
174 my $c = $compressors->{$ext}->{cmd};
175 $compressors->{$ext}->{bin} = `which $c 2>/dev/null`;
176 chomp($compressors->{$ext}->{bin});
179 sub detect_compressor_capable
181 my $filename = shift();
182 map { &detect_compressor_bin($_) } keys %$compressors
186 unless (grep {$filename =~ /\.(?:$_)$/} keys %$compressors);
187 # Loop through them, figure out which one it detected,
188 # and build the commandline.
190 foreach my $ext (keys %$compressors)
192 if ($filename =~ /\.(?:$ext)$/)
194 # Just die if compressor not found; if this occurs in the middle of
195 # two valid files with a lot of matches, error could easily be missed.
196 die("Didn't find $ext decompressor for $filename\n")
197 if ($compressors->{$ext}->{bin} eq '');
198 $cmdline = $compressors->{$ext}->{bin} ." ".
199 $compressors->{$ext}->{args};
209 $id_list{$id} = 1 if $line =~ m/$related_re/;
215 push @Mids, $id unless grep /\b$id\b/, @Mids;
216 my $re = join '|', @Mids;
217 $related_re = qr/$re/;
220 # The main program. Extract the pattern and make sure any relevant characters
221 # are quoted if the -l flag is given. The -t flag gives a time-on-queue value
222 # which is an additional condition. The -M flag will also display "related"
223 # loglines (msgid from matched lines is searched in following lines).
226 'I|sensitive' => sub { $insensitive = 0 },
227 'l|literal' => \$literal,
228 'M|related' => \$related,
229 't|queue-time=i' => \$queue_time,
230 'pager!' => \$use_pager,
231 'v|invert' => \$invert,
232 'h|help' => sub { pod2usage(-exit => 0, -verbose => 1) },
237 -noperldoc => system('perldoc -V 2>/dev/null >&2')
241 print basename($0) . ": $0\n",
242 "build: EXIM_RELEASE_VERSIONEXIM_VARIANT_VERSION\n",
243 "perl(runtime): $]\n";
246 ) and @ARGV or pod2usage;
248 $pattern = shift @ARGV;
249 $pattern = quotemeta $pattern if $literal;
251 # Start a pager if output goes to a terminal
252 if (-t 1 and $use_pager)
254 # for perl >= v5.10.x: foreach ($ENV{PAGER}//(), 'less', 'more')
255 foreach (defined $ENV{PAGER} ? $ENV{PAGER} : (), 'less', 'more')
257 local $ENV{LESS} .= ' --no-init --quit-if-one-screen';
258 open(my $pager, '|-', $_) or next;
264 # If file arguments are given, open each one and process according as it is
265 # is compressed or not.
272 if (-x 'ZCAT_COMMAND' && $filename =~ /\.(?:COMPRESS_SUFFIX)$/o)
274 open(LOG, "ZCAT_COMMAND $filename |") ||
275 die "Unable to zcat $filename: $!\n";
277 elsif (my $cmdline = &detect_compressor_capable($filename))
279 open(LOG, "$cmdline $filename |") ||
280 die "Unable to decompress $filename: $!\n";
284 open(LOG, "<$filename") || die "Unable to open $filename: $!\n";
286 do_line() while (<LOG>);
291 # If no files are named, process STDIN only
293 else { do_line() while (<STDIN>); }
295 # At the end of processing all the input, print any uncompleted messages.
299 print "+++ $_ has not completed +++\n$saved{$_}\n";
306 exigrep - search Exim's main log
310 B<exigrep> [options] pattern [log] ...
314 The B<exigrep> utility is a Perl script that searches one or more main log
315 files for entries that match a given pattern. When it finds a match,
316 it extracts all the log entries for the relevant message, not just
317 those that match the pattern. Thus, B<exigrep> can extract complete log
318 entries for a given message, or all mail for a given user, or for a
319 given host, for example.
321 If no file names are given on the command line, the standard input is read.
323 For known file extensions indicating compression (F<.gz>, F<.bz2>, F<.xz>,
324 F<.lzma>, and F<.zst>) a suitable de-compressor is used, if available.
326 The output is sent through a pager if a terminal is connected to STDOUT. As
327 pager are considered: C<$ENV{PAGER}>, C<less>, C<more>.
333 =item B<-l>|B<--literal>
335 This means 'literal', that is, treat all characters in the
336 pattern as standing for themselves. Otherwise the pattern must be a
337 Perl regular expression. The pattern match is case-insensitive.
339 =item B<-t>|B<--queue-time> I<seconds>
341 Limit the output to messages that spent at least I<seconds> in the
344 =item B<-I>|B<--sensitive>
346 Do a case sensitive search.
348 =item B<-v>|B<--invert>
350 Invert the meaning of the search pattern. That is, print message log
351 entries that are not related to that pattern.
353 =item B<-M>|B<--related>
355 Search for related messages too.
359 Do not use a pager, even if STDOUT is connected to a terminal.
361 =item B<-h>|B<--help>
363 Print a short reference help. For more detailed help try L<exigrep(8)>,
368 Print this manual page of B<exigrep>.
374 L<exim(8)>, L<perlre(1)>, L<Exim|http://exim.org/>
378 This manual page was stitched together from spec.txt by Andreas Metzler L<ametzler at downhill.at.eu.org>
379 and updated by Heiko Schlittermann L<hs@schlittermann.de>.