]> git.pld-linux.org Git - packages/exipick.git/blob - exipick.pl
- from http://jetmore.org/john/code/exipick
[packages/exipick.git] / exipick.pl
1 #!/usr/bin/perl
2
3 # SET THIS TO THE PATH TO YOUR SPOOL DIR!
4 my $spool   = '/var/spool/exim';
5 # SET THIS TO THE DEFAULT HEADER CHARACTER SET!
6 my $charset = 'ISO-8859-1';
7
8 # use 'exipick --help' to view documentation for this program.
9 # Documentation also viewable online at
10 #       http://www.exim.org/eximwiki/ToolExipickManPage
11
12 use strict;
13 use Getopt::Long;
14
15 my($p_name)   = $0 =~ m|/?([^/]+)$|;
16 my $p_version = "20061117.2";
17 my $p_usage   = "Usage: $p_name [--help|--version] (see --help for details)";
18 my $p_cp      = <<EOM;
19         Copyright (c) 2003-2006 John Jetmore <jj33\@pobox.com>
20
21     This program is free software; you can redistribute it and/or modify
22     it under the terms of the GNU General Public License as published by
23     the Free Software Foundation; either version 2 of the License, or
24     (at your option) any later version.
25
26     This program is distributed in the hope that it will be useful,
27     but WITHOUT ANY WARRANTY; without even the implied warranty of
28     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29     GNU General Public License for more details.
30
31     You should have received a copy of the GNU General Public License
32     along with this program; if not, write to the Free Software
33     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
34 EOM
35 ext_usage(); # before we do anything else, check for --help
36
37 $| = 1; # unbuffer STDOUT
38
39 Getopt::Long::Configure("bundling_override");
40 GetOptions(
41   'spool=s'     => \$G::spool,      # exim spool dir
42   'bp'          => \$G::mailq_bp,   # List the queue (noop - default)
43   'bpa'         => \$G::mailq_bpa,  # ... with generated address as well
44   'bpc'         => \$G::mailq_bpc,  # ... but just show a count of messages
45   'bpr'         => \$G::mailq_bpr,  # ... do not sort
46   'bpra'        => \$G::mailq_bpra, # ... with generated addresses, unsorted
47   'bpru'        => \$G::mailq_bpru, # ... only undelivered addresses, unsorted
48   'bpu'         => \$G::mailq_bpu,  # ... only undelivered addresses
49   'and'         => \$G::and,        # 'and' the criteria (default)
50   'or'          => \$G::or,         # 'or' the criteria
51   'f=s'         => \$G::qgrep_f,    # from regexp
52   'r=s'         => \$G::qgrep_r,    # recipient regexp
53   's=s'         => \$G::qgrep_s,    # match against size field
54   'y=s'         => \$G::qgrep_y,    # message younger than (secs)
55   'o=s'         => \$G::qgrep_o,    # message older than (secs)
56   'z'           => \$G::qgrep_z,    # frozen only
57   'x'           => \$G::qgrep_x,    # non-frozen only
58   'c'           => \$G::qgrep_c,    # display match count
59   'l'           => \$G::qgrep_l,    # long format (default)
60   'i'           => \$G::qgrep_i,    # message ids only
61   'b'           => \$G::qgrep_b,    # brief format
62   'size'        => \$G::size_only,  # sum the size of the matching msgs
63   'not'         => \$G::negate,     # flip every test
64   'R|reverse'   => \$G::reverse,    # reverse output (-R is qgrep option)
65   'sort=s'      => \@G::sort,       # allow you to choose variables to sort by
66   'freeze=s'    => \$G::freeze,     # freeze data in this file
67   'thaw=s'      => \$G::thaw,       # thaw data from this file
68   'unsorted'    => \$G::unsorted,   # unsorted, regardless of output format
69   'random'      => \$G::random,     # (poorly) randomize evaluation order
70   'flatq'       => \$G::flatq,      # brief format
71   'caseful'     => \$G::caseful,    # in '=' criteria, respect case
72   'caseless'    => \$G::caseless,   #   ...ignore case (default)
73   'charset=s'   => \$charset,       # charset for $bh and $h variables
74   'show-vars=s' => \$G::show_vars,  # display the contents of these vars
75   'just-vars'   => \$G::just_vars,  # only display vars, no other info
76   'show-rules'  => \$G::show_rules, # display compiled match rules
77   'show-tests'  => \$G::show_tests  # display tests as applied to each message
78 ) || exit(1);
79
80 # if both freeze and thaw specified, only thaw as it is less desctructive
81 $G::freeze = undef               if ($G::freeze && $G::thaw);
82 freeze_start()                   if ($G::freeze);
83 thaw_start()                     if ($G::thaw);
84
85 # massage sort options (make '$var,Var:' be 'var','var')
86 for (my $i = scalar(@G::sort)-1; $i >= 0; $i--) {
87   $G::sort[$i] = lc($G::sort[$i]);
88   $G::sort[$i] =~ s/[\$:\s]//g;
89   if ((my @vars = split(/,/, $G::sort[$i])) > 1) {
90     $G::sort[$i] = $vars[0]; shift(@vars); # replace current slot w/ first var
91     splice(@G::sort, $i+1, 0, @vars);      # add other vars after current pos
92   }
93 }
94 push(@G::sort, "message_exim_id") if (@G::sort);
95 die "empty value provided to --sort not allowed, exiting\n"
96     if (grep /^\s*$/, @G::sort);
97
98 # massage the qgrep options into standard criteria
99 push(@ARGV, "\$sender_address     =~ /$G::qgrep_f/") if ($G::qgrep_f);
100 push(@ARGV, "\$recipients         =~ /$G::qgrep_r/") if ($G::qgrep_r);
101 push(@ARGV, "\$shown_message_size eq $G::qgrep_s")   if ($G::qgrep_s);
102 push(@ARGV, "\$message_age        <  $G::qgrep_y")   if ($G::qgrep_y);
103 push(@ARGV, "\$message_age        >  $G::qgrep_o")   if ($G::qgrep_o);
104 push(@ARGV, "\$deliver_freeze")                      if ($G::qgrep_z);
105 push(@ARGV, "!\$deliver_freeze")                     if ($G::qgrep_x);
106
107 $G::mailq_bp        = $G::mailq_bp;        # shut up -w
108 $G::and             = $G::and;             # shut up -w
109 $G::msg_ids         = {};                  # short circuit when crit is only MID
110 $G::caseless        = $G::caseful ? 0 : 1; # nocase by default, case if both
111 @G::recipients_crit = ();                  # holds per-recip criteria
112 $spool              = $G::spool if ($G::spool);
113 my $count_only      = 1 if ($G::mailq_bpc  || $G::qgrep_c);
114 my $unsorted        = 1 if ($G::mailq_bpr  || $G::mailq_bpra ||
115                             $G::mailq_bpru || $G::unsorted);
116 my $msg             = $G::thaw ? thaw_message_list()
117                                : get_all_msgs($spool, $unsorted,
118                                               $G::reverse, $G::random);
119 die "Problem accessing thaw file\n" if ($G::thaw && !$msg);
120 my $crit            = process_criteria(\@ARGV);
121 my $e               = Exim::SpoolFile->new();
122 my $tcount          = 0 if ($count_only);  # holds count of all messages
123 my $mcount          = 0 if ($count_only);  # holds count of matching messages
124 my $total_size      = 0 if ($G::size_only);
125 $e->set_undelivered_only(1)      if ($G::mailq_bpru || $G::mailq_bpu);
126 $e->set_show_generated(1)        if ($G::mailq_bpra || $G::mailq_bpa);
127 $e->output_long()                if ($G::qgrep_l);
128 $e->output_idonly()              if ($G::qgrep_i);
129 $e->output_brief()               if ($G::qgrep_b);
130 $e->output_flatq()               if ($G::flatq);
131 $e->output_vars_only()           if ($G::just_vars && $G::show_vars);
132 $e->set_show_vars($G::show_vars) if ($G::show_vars);
133 $e->set_spool($spool);
134
135 MSG:
136 foreach my $m (@$msg) {
137   next if (scalar(keys(%$G::msg_ids)) && !$G::or
138                                       && !$G::msg_ids->{$m->{message}});
139   if ($G::thaw) {
140     my $data = thaw_data();
141     if (!$e->restore_state($data)) {
142       warn "Couldn't thaw $data->{_message}: ".$e->error()."\n";
143       next MSG;
144     }
145   } else {
146     if (!$e->parse_message($m->{message}, $m->{path})) {
147       warn "Couldn't parse $m->{message}: ".$e->error()."\n";
148       next MSG;
149     }
150   }
151   $tcount++;
152   my $match = 0;
153   my @local_crit = ();
154   foreach my $c (@G::recipients_crit) {              # handle each_recip* vars
155     foreach my $addr (split(/, /, $e->get_var($c->{var}))) {
156       my %t = ( 'cmp' => $c->{cmp}, 'var' => $c->{var} );
157       $t{cmp} =~ s/"?\$var"?/'$addr'/;
158       push(@local_crit, \%t);
159     }
160   }
161   if ($G::show_tests) { print $e->get_var('message_exim_id'), "\n"; }
162   CRITERIA:
163   foreach my $c (@$crit, @local_crit) {
164     my $var = $e->get_var($c->{var});
165     my $ret = eval($c->{cmp});
166     if ($G::show_tests) {
167       printf "  %25s =  '%s'\n  %25s => $ret\n",$c->{var},$var,$c->{cmp},$ret;
168     }
169     if ($@) {
170       print STDERR "Error in eval '$c->{cmp}': $@\n";
171       next MSG;
172     } elsif ($ret) {
173       $match = 1;
174       if ($G::or) { last CRITERIA; }
175       else        { next CRITERIA; }
176     } else { # no match
177       if ($G::or) { next CRITERIA; }
178       else        { next MSG;      }
179     }
180   }
181
182   # skip this message if any criteria were supplied and it didn't match
183   next MSG if ((scalar(@$crit) || scalar(@local_crit)) && !$match);
184
185   if ($count_only || $G::size_only) {
186     $mcount++;
187     $total_size += $e->get_var('message_size');
188   } else {
189     if (@G::sort) {
190       # if we are defining criteria to sort on, save the message here.  If
191       # we don't save here and do the sort later, we have a chicken/egg
192       # problem
193       push(@G::to_print, { vars => {}, output => "" });
194       foreach my $var (@G::sort) {
195         # save any values we want to sort on.  I don't like doing the internal
196         # struct access here, but calling get_var a bunch can be _slow_ =(
197         $G::sort_type{$var} ||= '<=>';
198         $G::to_print[-1]{vars}{$var} = $e->{_vars}{$var};
199         $G::sort_type{$var} = 'cmp' if ($G::to_print[-1]{vars}{$var} =~ /\D/);
200       }
201       $G::to_print[-1]{output} = $e->format_message();
202     } else {
203       print $e->format_message();
204     }
205   }
206
207   if ($G::freeze) {
208     freeze_data($e->get_state());
209     push(@G::frozen_msgs, $m);
210   }
211 }
212
213 if (@G::to_print) {
214   msg_sort(\@G::to_print, \@G::sort, $G::reverse);
215   foreach my $msg (@G::to_print) {
216     print $msg->{output};
217   }
218 }
219
220 if ($G::qgrep_c) {
221   print "$mcount matches out of $tcount messages" .
222         ($G::size_only ? " ($total_size)" : "") . "\n";
223 } elsif ($G::mailq_bpc) {
224   print "$mcount" .  ($G::size_only ? " ($total_size)" : "") . "\n";
225 } elsif ($G::size_only) {
226   print "$total_size\n";
227 }
228
229 if ($G::freeze) {
230   freeze_message_list(\@G::frozen_msgs);
231   freeze_end();
232 } elsif ($G::thaw) {
233   thaw_end();
234 }
235
236 exit;
237
238 # sender_address_domain,shown_message_size
239 sub msg_sort {
240   my $msgs    = shift;
241   my $vars    = shift;
242   my $reverse = shift;
243
244   my @pieces = ();
245   foreach my $v (@G::sort) {
246     push(@pieces, "\$a->{vars}{\"$v\"} $G::sort_type{$v} \$b->{vars}{\"$v\"}");
247   }
248   my $sort_str = join(" || ", @pieces);
249
250   @$msgs = sort { eval $sort_str } (@$msgs);
251   @$msgs = reverse(@$msgs) if ($reverse);
252 }
253
254 sub try_load {
255   my $mod = shift;
256
257   eval("use $mod");
258   return $@ ? 0 : 1;
259 }
260
261 # FREEZE FILE FORMAT:
262 # message_data_bytes
263 # message_data
264 # <...>
265 # EOM
266 # message_list
267 # message_list_bytes <- 10 bytes, zero-packed, plus \n
268
269 sub freeze_start {
270   eval("use Storable");
271   die "Storable module not found: $@\n" if ($@);
272   open(O, ">$G::freeze") || die "Can't open freeze file $G::freeze: $!\n";
273   $G::freeze_handle = \*O;
274 }
275
276 sub freeze_end {
277   close($G::freeze_handle);
278 }
279
280 sub thaw_start {
281   eval("use Storable");
282   die "Storable module not found: $@\n" if ($@);
283   open(I, "<$G::thaw") || die "Can't open freeze file $G::thaw: $!\n";
284   $G::freeze_handle = \*I;
285 }
286
287 sub thaw_end {
288   close($G::freeze_handle);
289 }
290
291 sub freeze_data {
292   my $h = Storable::freeze($_[0]);
293   print $G::freeze_handle length($h)+1, "\n$h\n";
294 }
295
296 sub freeze_message_list {
297   my $h = Storable::freeze($_[0]);
298   my $l = length($h) + 1;
299   printf $G::freeze_handle "EOM\n$l\n$h\n%010d\n", $l+11+length($l)+1;
300 }
301
302 sub thaw_message_list {
303   my $orig_pos = tell($G::freeze_handle);
304   seek($G::freeze_handle, -11, 2);
305   chomp(my $bytes = <$G::freeze_handle>);
306   seek($G::freeze_handle, $bytes * -1, 2);
307   my $obj = thaw_data();
308   seek($G::freeze_handle, 0, $orig_pos);
309   return($obj);
310 }
311
312 sub thaw_data {
313   my $obj;
314   chomp(my $bytes = <$G::freeze_handle>);
315   return(undef) if (!$bytes || $bytes eq 'EOM');
316   my $read = read(I, $obj, $bytes);
317   die "Format error in thaw file (expected $bytes bytes, got $read)\n"
318       if ($bytes != $read);
319   chomp($obj);
320   return(Storable::thaw($obj));
321 }
322
323 sub process_criteria {
324   my $a = shift;
325   my @c = ();
326   my $e = 0;
327
328   foreach (@$a) {
329     foreach my $t ('@') { s/$t/\\$t/g; }
330     if (/^(.*?)\s+(<=|>=|==|!=|<|>)\s+(.*)$/) {
331       #print STDERR "found as integer\n";
332       my $v = $1; my $o = $2; my $n = $3;
333       if    ($n =~ /^(-?[\d\.]+)M$/)  { $n = $1 * 1024 * 1024; }
334       elsif ($n =~ /^(-?[\d\.]+)K$/)  { $n = $1 * 1024; }
335       elsif ($n =~ /^(-?[\d\.]+)B?$/) { $n = $1; }
336       elsif ($n =~ /^(-?[\d\.]+)d$/)  { $n = $1 * 60 * 60 * 24; }
337       elsif ($n =~ /^(-?[\d\.]+)h$/)  { $n = $1 * 60 * 60; }
338       elsif ($n =~ /^(-?[\d\.]+)m$/)  { $n = $1 * 60; }
339       elsif ($n =~ /^(-?[\d\.]+)s?$/) { $n = $1; }
340       else {
341         print STDERR "Expression $_ did not parse: numeric comparison with ",
342                      "non-number\n";
343         $e = 1;
344         next;
345       }
346       push(@c, { var => lc($v), cmp => "(\$var $o $n)" });
347     } elsif (/^(.*?)\s+(=~|!~)\s+(.*)$/) {
348       #print STDERR "found as string regexp\n";
349       push(@c, { var => lc($1), cmp => "(\"\$var\" $2 $3)" });
350     } elsif (/^(.*?)\s+=\s+(.*)$/) {
351       #print STDERR "found as bare string regexp\n";
352       my $case = $G::caseful ? '' : 'i';
353       push(@c, { var => lc($1), cmp => "(\"\$var\" =~ /$2/$case)" });
354       # quote special characters in perl text string
355       #foreach my $t ('@') { $c[-1]{cmp} =~ s/$t/\\$t/g; }
356     } elsif (/^(.*?)\s+(eq|ne)\s+(.*)$/) {
357       #print STDERR "found as string cmp\n";
358       my $var = lc($1); my $op = $2; my $val = $3;
359       $val =~ s|^(['"])(.*)\1$|$2|;
360       push(@c, { var => $var, cmp => "(\"\$var\" $op \"$val\")" });
361       if (($var eq 'message_id' || $var eq 'message_exim_id') && $op eq "eq") {
362         #print STDERR "short circuit @c[-1]->{cmp} $val\n";
363         $G::msg_ids->{$val} = 1;
364       }
365       #foreach my $t ('@') { $c[-1]{cmp} =~ s/$t/\\$t/g; }
366     } elsif (/^(\S+)$/) {
367       #print STDERR "found as boolean\n";
368       push(@c, { var => lc($1), cmp => "(\$var)" });
369     } else {
370       print STDERR "Expression $_ did not parse\n";
371       $e = 1;
372       next;
373     }
374     # assign the results of the cmp test here (handle "!" negation)
375     # also handle global --not negation
376     if ($c[-1]{var} =~ s|^!||) {
377       $c[-1]{cmp} .= $G::negate ? " ? 1 : 0" : " ? 0 : 1";
378     } else {
379       $c[-1]{cmp} .= $G::negate ? " ? 0 : 1" : " ? 1 : 0";
380     }
381     # support the each_* psuedo variables.  Steal the criteria off of the
382     # queue for special processing later
383     if ($c[-1]{var} =~ /^each_(recipients(_(un)?del)?)$/) {
384       my $var = $1;
385       push(@G::recipients_crit,pop(@c));
386       $G::recipients_crit[-1]{var} = $var; # remove each_ from the variable
387     }
388   }
389
390   exit(1) if ($e);
391
392   if ($G::show_rules) { foreach (@c) { print "$_->{var}\t$_->{cmp}\n"; } }
393
394   return(\@c);
395 }
396
397 sub get_all_msgs {
398   my $d = shift() . '/input';
399   my $u = shift; # don't sort
400   my $r = shift; # right before returning, reverse order
401   my $o = shift; # if true, randomize list order before returning
402   my @m = ();
403
404   opendir(D, "$d") || die "Couldn't opendir $d: $!\n";
405   foreach my $e (grep !/^\./, readdir(D)) {
406     if ($e =~ /^[a-zA-Z0-9]$/) {
407       opendir(DD, "$d/$e") || next;
408       foreach my $f (grep !/^\./, readdir(DD)) {
409         push(@m, { message => $1, path => "$d/$e" }) if ($f =~ /^(.{16})-H$/);
410       }
411       closedir(DD);
412     } elsif ($e =~ /^(.{16})-H$/) {
413       push(@m, { message => $1, path => $d });
414     }
415   }
416   closedir(D);
417
418   if ($o) {
419     my $c = scalar(@m);
420     # loop twice to pretend we're doing a good job of mixing things up
421     for (my $i = 0; $i < 2 * $c; $i++) {
422       my $rand = int(rand($c));
423       ($m[$i % $c],$m[$rand]) = ($m[$rand],$m[$i % $c]);
424     }
425   } elsif (!$u) {
426     @m = sort { $a->{message} cmp $b->{message} } @m;
427   }
428   @m = reverse(@m) if ($r);
429
430   return(\@m);
431 }
432
433 BEGIN {
434
435 package Exim::SpoolFile;
436
437 # versions 4.61 and higher will not need these variables anymore, but they
438 # are left for handling legacy installs
439 $Exim::SpoolFile::ACL_C_MAX_LEGACY = 10;
440 #$Exim::SpoolFile::ACL_M_MAX _LEGACY= 10;
441
442 sub new {
443   my $class = shift;
444   my $self  = {};
445   bless($self, $class);
446
447   $self->{_spool_dir}        = '';
448   $self->{_undelivered_only} = 0;
449   $self->{_show_generated}   = 0;
450   $self->{_output_long}      = 1;
451   $self->{_output_idonly}    = 0;
452   $self->{_output_brief}     = 0;
453   $self->{_output_flatq}     = 0;
454   $self->{_output_vars_only} = 0;
455   $self->{_show_vars}        = [];
456
457   $self->_reset();
458   return($self);
459 }
460
461 sub output_long {
462   my $self = shift;
463
464   $self->{_output_long}      = 1;
465   $self->{_output_idonly}    = 0;
466   $self->{_output_brief}     = 0;
467   $self->{_output_flatq}     = 0;
468   $self->{_output_vars_only} = 0;
469 }
470
471 sub output_idonly {
472   my $self = shift;
473
474   $self->{_output_long}      = 0;
475   $self->{_output_idonly}    = 1;
476   $self->{_output_brief}     = 0;
477   $self->{_output_flatq}     = 0;
478   $self->{_output_vars_only} = 0;
479 }
480
481 sub output_brief {
482   my $self = shift;
483
484   $self->{_output_long}      = 0;
485   $self->{_output_idonly}    = 0;
486   $self->{_output_brief}     = 1;
487   $self->{_output_flatq}     = 0;
488   $self->{_output_vars_only} = 0;
489 }
490
491 sub output_flatq {
492   my $self = shift;
493
494   $self->{_output_long}      = 0;
495   $self->{_output_idonly}    = 0;
496   $self->{_output_brief}     = 0;
497   $self->{_output_flatq}     = 1;
498   $self->{_output_vars_only} = 0;
499 }
500
501 sub output_vars_only {
502   my $self = shift;
503
504   $self->{_output_long}      = 0;
505   $self->{_output_idonly}    = 0;
506   $self->{_output_brief}     = 0;
507   $self->{_output_flatq}     = 0;
508   $self->{_output_vars_only} = 1;
509 }
510
511 sub set_show_vars {
512   my $self = shift;
513   my $s    = shift;
514
515   foreach my $v (split(/\s*,\s*/, $s)) {
516     push(@{$self->{_show_vars}}, $v);
517   }
518 }
519
520 sub set_show_generated {
521   my $self = shift;
522   $self->{_show_generated} = shift;
523 }
524
525 sub set_undelivered_only {
526   my $self = shift;
527   $self->{_undelivered_only} = shift;
528 }
529
530 sub error {
531   my $self = shift;
532   return $self->{_error};
533 }
534
535 sub _error {
536   my $self = shift;
537   $self->{_error} = shift;
538   return(undef);
539 }
540
541 sub _reset {
542   my $self = shift;
543
544   $self->{_error}       = '';
545   $self->{_delivered}   = 0;
546   $self->{_message}     = '';
547   $self->{_path}        = '';
548   $self->{_vars}        = {};
549   $self->{_vars_raw}    = {};
550
551   $self->{_numrecips}   = 0;
552   $self->{_udel_tree}   = {};
553   $self->{_del_tree}    = {};
554   $self->{_recips}      = {};
555
556   return($self);
557 }
558
559 sub parse_message {
560   my $self = shift;
561
562   $self->_reset();
563   $self->{_message} = shift || return(0);
564   $self->{_path}    = shift; # optional path to message
565   return(0) if (!$self->{_spool_dir});
566   if (!$self->{_path} && !$self->_find_path()) {
567     # assume the message was delivered from under us and ignore
568     $self->{_delivered} = 1;
569     return(1);
570   }
571   $self->_parse_header() || return(0);
572
573   return(1);
574 }
575
576 # take the output of get_state() and set up a message internally like
577 # parse_message (except from a saved data struct, not by parsing the
578 # files on disk).
579 sub restore_state {
580   my $self = shift;
581   my $h    = shift;
582
583   return(1) if ($h->{_delivered});
584   $self->_reset();
585   $self->{_message} = $h->{_message} || return(0);
586   return(0) if (!$self->{_spool_dir});
587
588   $self->{_path}      = $h->{_path};
589   $self->{_vars}      = $h->{_vars};
590   $self->{_numrecips} = $h->{_numrecips};
591   $self->{_udel_tree} = $h->{_udel_tree};
592   $self->{_del_tree}  = $h->{_del_tree};
593   $self->{_recips}    = $h->{_recips};
594
595   $self->{_vars}{message_age} = time() - $self->{_vars}{received_time};
596   return(1);
597 }
598
599 # This returns the state data for a specific message in a format that can
600 # be later frozen back in to regain state
601 #
602 # after calling this function, this specific state is not expect to be
603 # reused.  That's because we're returning direct references to specific
604 # internal structures.  We're also modifying the structure ourselves
605 # by deleting certain internal message variables.
606 sub get_state {
607   my $self = shift;
608   my $h    = {};    # this is the hash ref we'll be returning.
609
610   $h->{_delivered} = $self->{_delivered};
611   $h->{_message}   = $self->{_message};
612   $h->{_path}      = $self->{_path};
613   $h->{_vars}      = $self->{_vars};
614   $h->{_numrecips} = $self->{_numrecips};
615   $h->{_udel_tree} = $self->{_udel_tree};
616   $h->{_del_tree}  = $self->{_del_tree};
617   $h->{_recips}    = $self->{_recips};
618
619   # delete some internal variables that we will rebuild later if needed
620   delete($h->{_vars}{message_body});
621   delete($h->{_vars}{message_age});
622
623   return($h);
624 }
625
626 # keep this sub as a feature if we ever break this module out, but do away
627 # with its use in exipick (pass it in from caller instead)
628 sub _find_path {
629   my $self = shift;
630
631   return(0) if (!$self->{_message});
632   return(0) if (!$self->{_spool_dir});
633
634   # test split spool first on the theory that people concerned about
635   # performance will have split spool set =).
636   foreach my $f (substr($self->{_message}, 5, 1).'/', '') {
637     if (-f "$self->{_spool_dir}/input/$f$self->{_message}-H") {
638       $self->{_path} = $self->{_spool_dir} . "/input/$f";
639       return(1);
640     }
641   }
642   return(0);
643 }
644
645 sub set_spool {
646   my $self = shift;
647   $self->{_spool_dir} = shift;
648 }
649
650 sub get_matching_vars {
651   my $self = shift;
652   my $e    = shift;
653
654   if ($e =~ /^\^/) {
655     my @r = ();
656     foreach my $v (keys %{$self->{_vars}}) { push(@r, $v) if ($v =~ /$e/); }
657     return(@r);
658   } else {
659     return($e);
660   }
661 }
662
663 # accepts a variable with or without leading '$' or trailing ':'
664 sub get_var {
665   my $self = shift;
666   my $var  = lc(shift); $var =~ s/^\$//; $var =~ s/:$//;
667
668   if ($var eq 'message_body' && !defined($self->{_vars}{message_body})) {
669     $self->_parse_body()
670   } elsif ($var =~ s|^([rb]?h)(eader)?_|${1}eader_| &&
671            exists($self->{_vars}{$var}) && !defined($self->{_vars}{$var}))
672   {
673     if ((my $type = $1) eq 'rh') {
674       $self->{_vars}{$var} = join('', @{$self->{_vars_raw}{$var}{vals}});
675     } else {
676       # both bh_ and h_ build their strings from rh_.  Do common work here
677       my $rh = $var; $rh =~ s|^b?|r|;
678       my $comma = 1 if ($self->{_vars_raw}{$rh}{type} =~ /^[BCFRST]$/);
679       foreach (@{$self->{_vars_raw}{$rh}{vals}}) {
680         my $x = $_; # editing $_ here would change the original, which is bad
681         $x =~ s|^\s+||;
682         $x =~ s|\s+$||;
683         if ($comma) { chomp($x); $self->{_vars}{$var} .= "$x,\n"; }
684         else        { $self->{_vars}{$var} .= $x; }
685       }
686       $self->{_vars}{$var} =~ s|[\s\n]*$||;
687       $self->{_vars}{$var} =~ s|,$|| if ($comma);
688       # ok, that's the preprocessing, not do specific processing for h type
689       if ($type eq 'bh') {
690         $self->{_vars}{$var} = $self->_decode_2047($self->{_vars}{$var});
691       } else {
692         $self->{_vars}{$var} =
693             $self->_decode_2047($self->{_vars}{$var}, $charset);
694       }
695     }
696   }
697   elsif ($var eq 'received_count' && !defined($self->{_vars}{received_count}))
698   {
699     $self->{_vars}{received_count} =
700         scalar(@{$self->{_vars_raw}{rheader_received}{vals}});
701   }
702   elsif ($var eq 'message_headers' && !defined($self->{_vars}{message_headers}))
703   {
704     $self->{_vars}{$var} =
705         $self->_decode_2047($self->{_vars}{message_headers_raw}, $charset);
706     chomp($self->{_vars}{$var});
707   }
708   elsif ($var eq 'reply_address' && !defined($self->{_vars}{reply_address}))
709   {
710     $self->{_vars}{reply_address} = exists($self->{_vars}{"header_reply-to"})
711         ? $self->get_var("header_reply-to") : $self->get_var("header_from");
712   }
713
714   #chomp($self->{_vars}{$var}); # I think this was only for headers, obsolete
715   return $self->{_vars}{$var};
716 }
717
718 sub _decode_2047 {
719   my $self = shift;
720   my $s    = shift; # string to decode
721   my $c    = shift; # target charset.  If empty, just decode, don't convert
722   my $t    = '';    # the translated string
723   my $e    = 0;     # set to true if we get an error in here anywhere
724
725   return($s) if ($s !~ /=\?/); # don't even bother to look if there's no sign
726
727   my @p = ();
728   foreach my $mw (split(/(=\?[^\?]{3,}\?[BQ]\?[^\?]{1,74}\?=)/i, $s)) {
729     next if ($mw eq '');
730     if ($mw =~ /=\?([^\?]{3,})\?([BQ])\?([^\?]{1,74})\?=/i) {
731       push(@p, { data => $3, encoding => uc($2), charset => uc($1),
732                  is_mime => 1 });
733       if ($p[-1]{encoding} eq 'Q') {
734         my @ow = split('', $p[-1]{data});
735         my @nw = ();
736         for (my $i = 0; $i < @ow; $i++) {
737           if ($ow[$i] eq '_') { push(@nw, ' '); }
738           elsif ($ow[$i] eq '=') {
739             if (scalar(@ow) - ($i+1) < 2) {  # ran out of characters
740               $e = 1; last;
741             } elsif ($ow[$i+1] !~ /[\dA-F]/i || $ow[$i+2] !~ /[\dA-F]/i) {
742               $e = 1; last;
743             } else {
744               #push(@nw, chr('0x'.$ow[$i+1].$ow[$i+2]));
745               push(@nw, pack("C", hex($ow[$i+1].$ow[$i+2])));
746               $i += 2;
747             }
748           }
749           elsif ($ow[$i] =~ /\s/) { # whitspace is illegal
750             $e = 1;
751             last;
752           }
753           else { push(@nw, $ow[$i]); }
754         }
755         $p[-1]{data} = join('', @nw);
756       } elsif ($p[-1]{encoding} eq 'B') {
757         my $x = $p[-1]{data};
758         $x    =~ tr#A-Za-z0-9+/##cd;
759         $x    =~ s|=+$||;
760         $x    =~ tr#A-Za-z0-9+/# -_#;
761         my $r = '';
762         while ($x =~ s/(.{1,60})//s) {
763           $r .= unpack("u", chr(32 + int(length($1)*3/4)) . $1);
764         }
765         $p[-1]{data} = $r;
766       }
767     } else {
768       push(@p, { data => $mw, is_mime => 0,
769                  is_ws => ($mw =~ m|^[\s\n]+|sm) ? 1 : 0 });
770     }
771   }
772
773   for (my $i = 0; $i < @p; $i++) {
774     # mark entities we want to skip (whitespace between consecutive mimewords)
775     if ($p[$i]{is_mime} && $p[$i+1]{is_ws} && $p[$i+2]{is_mime}) {
776       $p[$i+1]{skip} = 1;
777     }
778
779     # if word is a mimeword and we have access to Encode and charset was
780     # specified, try to convert text
781     # XXX _cannot_ get consistent conversion results in perl, can't get them
782     # to return same conversions that exim performs.  Until I can figure this
783     # out, don't attempt any conversions (header_ will return same value as
784     # bheader_).
785     #if ($c && $p[$i]{is_mime} && $self->_try_load('Encode')) {
786     #  # XXX not sure how to catch errors here
787     #  Encode::from_to($p[$i]{data}, $p[$i]{charset}, $c);
788     #}
789
790     # replace binary zeros w/ '?' in decoded text
791     if ($p[$i]{is_mime}) { $p[$i]{data} =~ s|\x00|?|g; }
792   }
793
794   if ($e) {
795     return($s);
796   } else {
797     return(join('', map { $_->{data} } grep { !$_->{skip} } @p));
798   }
799 }
800
801 # This isn't a class func but I'm tired
802 sub _try_load {
803   my $self = shift;
804   my $mod  = shift;
805
806   eval("use $mod");
807   return $@ ? 0 : 1;
808 }
809
810 sub _parse_body {
811   my $self = shift;
812   my $f    = $self->{_path} . '/' . $self->{_message} . '-D';
813   $self->{_vars}{message_body} = ""; # define var so we only come here once
814
815   open(I, "<$f") || return($self->_error("Couldn't open $f: $!"));
816   chomp($_ = <I>);
817   return(0) if ($self->{_message}.'-D' ne $_);
818
819   $self->{_vars}{message_body} = join('', <I>);
820   close(I);
821   $self->{_vars}{message_body} =~ s/\n/ /g;
822   $self->{_vars}{message_body} =~ s/\000/ /g;
823   return(1);
824 }
825
826 sub _parse_header {
827   my $self = shift;
828   my $f    = $self->{_path} . '/' . $self->{_message} . '-H';
829
830   if (!open(I, "<$f")) {
831     # assume message went away and silently ignore
832     $self->{_delivered} = 1;
833     return(1);
834   }
835
836   # There are a few numeric variables that should explicitly be set to
837   # zero if they aren't found in the header.  Technically an empty value
838   # works just as well, but might as well be pedantic
839   $self->{_vars}{body_zerocount}           = 0;
840   $self->{_vars}{host_lookup_deferred}     = 0;
841   $self->{_vars}{host_lookup_failed}       = 0;
842   $self->{_vars}{tls_certificate_verified} = 0;
843
844   chomp($_ = <I>);
845   return(0) if ($self->{_message}.'-H' ne $_);
846   $self->{_vars}{message_id}       = $self->{_message};
847   $self->{_vars}{message_exim_id}  = $self->{_message};
848
849   # line 2
850   chomp($_ = <I>);
851   return(0) if (!/^(.+)\s(\-?\d+)\s(\-?\d+)$/);
852   $self->{_vars}{originator_login} = $1;
853   $self->{_vars}{originator_uid}   = $2;
854   $self->{_vars}{originator_gid}   = $3;
855
856   # line 3
857   chomp($_ = <I>);
858   return(0) if (!/^<(.*)>$/);
859   $self->{_vars}{sender_address}   = $1;
860   $self->{_vars}{sender_address_domain} = $1;
861   $self->{_vars}{sender_address_local_part} = $1;
862   $self->{_vars}{sender_address_domain} =~ s/^.*\@//;
863   $self->{_vars}{sender_address_local_part} =~ s/^(.*)\@.*$/$1/;
864
865   # line 4
866   chomp($_ = <I>);
867   return(0) if (!/^(\d+)\s(\d+)$/);
868   $self->{_vars}{received_time}    = $1;
869   $self->{_vars}{warning_count}    = $2;
870   $self->{_vars}{message_age}      = time() - $self->{_vars}{received_time};
871
872   while (<I>) {
873     chomp();
874     if (/^(-\S+)\s*(.*$)/) {
875       my $tag = $1;
876       my $arg = $2;
877       if ($tag eq '-acl') {
878         my $t;
879         return(0) if ($arg !~ /^(\d+)\s(\d+)$/);
880         if ($1 < $Exim::SpoolFile::ACL_C_MAX_LEGACY) {
881           $t = "acl_c$1";
882         } else {
883           $t = "acl_m" . ($1 - $Exim::SpoolFile::ACL_C_MAX_LEGACY);
884         }
885         read(I, $self->{_vars}{$t}, $2+1) || return(0);
886         chomp($self->{_vars}{$t});
887       } elsif ($tag eq '-aclc') {
888         #return(0) if ($arg !~ /^(\d+)\s(\d+)$/);
889         return(0) if ($arg !~ /^(\S+)\s(\d+)$/);
890         my $t = "acl_c$1";
891         read(I, $self->{_vars}{$t}, $2+1) || return(0);
892         chomp($self->{_vars}{$t});
893       } elsif ($tag eq '-aclm') {
894         #return(0) if ($arg !~ /^(\d+)\s(\d+)$/);
895         return(0) if ($arg !~ /^(\S+)\s(\d+)$/);
896         my $t = "acl_m$1";
897         read(I, $self->{_vars}{$t}, $2+1) || return(0);
898         chomp($self->{_vars}{$t});
899       } elsif ($tag eq '-local') {
900         $self->{_vars}{sender_local} = 1;
901       } elsif ($tag eq '-localerror') {
902         $self->{_vars}{local_error_message} = 1;
903       } elsif ($tag eq '-local_scan') {
904         $self->{_vars}{local_scan_data} = $arg;
905       } elsif ($tag eq '-spam_score_int') {
906         $self->{_vars}{spam_score_int} = $arg;
907         $self->{_vars}{spam_score}     = $arg / 10;
908       } elsif ($tag eq '-bmi_verdicts') {
909         $self->{_vars}{bmi_verdicts} = $arg;
910       } elsif ($tag eq '-host_lookup_deferred') {
911         $self->{_vars}{host_lookup_deferred} = 1;
912       } elsif ($tag eq '-host_lookup_failed') {
913         $self->{_vars}{host_lookup_failed} = 1;
914       } elsif ($tag eq '-body_linecount') {
915         $self->{_vars}{body_linecount} = $arg;
916       } elsif ($tag eq '-body_zerocount') {
917         $self->{_vars}{body_zerocount} = $arg;
918       } elsif ($tag eq '-frozen') {
919         $self->{_vars}{deliver_freeze} = 1;
920         $self->{_vars}{deliver_frozen_at} = $arg;
921       } elsif ($tag eq '-allow_unqualified_recipient') {
922         $self->{_vars}{allow_unqualified_recipient} = 1;
923       } elsif ($tag eq '-allow_unqualified_sender') {
924         $self->{_vars}{allow_unqualified_sender} = 1;
925       } elsif ($tag eq '-deliver_firsttime') {
926         $self->{_vars}{deliver_firsttime} = 1;
927         $self->{_vars}{first_delivery} = 1;
928       } elsif ($tag eq '-manual_thaw') {
929         $self->{_vars}{deliver_manual_thaw} = 1;
930         $self->{_vars}{manually_thawed} = 1;
931       } elsif ($tag eq '-auth_id') {
932         $self->{_vars}{authenticated_id} = $arg;
933       } elsif ($tag eq '-auth_sender') {
934         $self->{_vars}{authenticated_sender} = $arg;
935       } elsif ($tag eq '-sender_set_untrusted') {
936         $self->{_vars}{sender_set_untrusted} = 1;
937       } elsif ($tag eq '-tls_certificate_verified') {
938         $self->{_vars}{tls_certificate_verified} = 1;
939       } elsif ($tag eq '-tls_cipher') {
940         $self->{_vars}{tls_cipher} = $arg;
941       } elsif ($tag eq '-tls_peerdn') {
942         $self->{_vars}{tls_peerdn} = $arg;
943       } elsif ($tag eq '-host_address') {
944         $self->{_vars}{sender_host_port} = $self->_get_host_and_port(\$arg);
945         $self->{_vars}{sender_host_address} = $arg;
946       } elsif ($tag eq '-interface_address') {
947         $self->{_vars}{received_port} =
948             $self->{_vars}{interface_port} = $self->_get_host_and_port(\$arg);
949         $self->{_vars}{received_ip_address} =
950             $self->{_vars}{interface_address} = $arg;
951       } elsif ($tag eq '-active_hostname') {
952         $self->{_vars}{smtp_active_hostname} = $arg;
953       } elsif ($tag eq '-host_auth') {
954         $self->{_vars}{sender_host_authenticated} = $arg;
955       } elsif ($tag eq '-host_name') {
956         $self->{_vars}{sender_host_name} = $arg;
957       } elsif ($tag eq '-helo_name') {
958         $self->{_vars}{sender_helo_name} = $arg;
959       } elsif ($tag eq '-ident') {
960         $self->{_vars}{sender_ident} = $arg;
961       } elsif ($tag eq '-received_protocol') {
962         $self->{_vars}{received_protocol} = $arg;
963       } elsif ($tag eq '-N') {
964         $self->{_vars}{dont_deliver} = 1;
965       } else {
966         # unrecognized tag, save it for reference
967         $self->{$tag} = $arg;
968       }
969     } else {
970       last;
971     }
972   }
973
974   # when we drop out of the while loop, we have the first line of the
975   # delivered tree in $_
976   do {
977     if ($_ eq 'XX') {
978       ; # noop
979     } elsif ($_ =~ s/^[YN][YN]\s+//) {
980       $self->{_del_tree}{$_} = 1;
981     } else {
982       return(0);
983     }
984     chomp($_ = <I>);
985   } while ($_ !~ /^\d+$/);
986
987   $self->{_numrecips} = $_;
988   $self->{_vars}{recipients_count} = $self->{_numrecips};
989   for (my $i = 0; $i < $self->{_numrecips}; $i++) {
990     chomp($_ = <I>);
991     return(0) if (/^$/);
992     my $addr = '';
993     if (/^(.*)\s\d+,(\d+),\d+$/) {
994       #print STDERR "exim3 type (untested): $_\n";
995       $self->{_recips}{$1} = { pno => $2 };
996       $addr = $1;
997     } elsif (/^(.*)\s(\d+)$/) {
998       #print STDERR "exim4 original type (untested): $_\n";
999       $self->{_recips}{$1} = { pno => $2 };
1000       $addr = $1;
1001     } elsif (/^(.*)\s(.*)\s(\d+),(\d+)#1$/) {
1002       #print STDERR "exim4 new type #1 (untested): $_\n";
1003       return($self->_error("incorrect format: $_")) if (length($2) != $3);
1004       $self->{_recips}{$1} = { pno => $4, errors_to => $2 };
1005       $addr = $1;
1006     } elsif (/^.*#(\d+)$/) {
1007       #print STDERR "exim4 #$1 style (unimplemented): $_\n";
1008       $self->_error("exim4 #$1 style (unimplemented): $_");
1009     } else {
1010       #print STDERR "default type: $_\n";
1011       $self->{_recips}{$_} = {};
1012       $addr = $_;
1013     }
1014     $self->{_udel_tree}{$addr} = 1 if (!$self->{_del_tree}{$addr});
1015   }
1016   $self->{_vars}{recipients}         = join(', ', keys(%{$self->{_recips}}));
1017   $self->{_vars}{recipients_del}     = join(', ', keys(%{$self->{_del_tree}}));
1018   $self->{_vars}{recipients_undel}   = join(', ', keys(%{$self->{_udel_tree}}));
1019   $self->{_vars}{recipients_undel_count} = scalar(keys(%{$self->{_udel_tree}}));
1020   $self->{_vars}{recipients_del_count}   = 0;
1021   foreach my $r (keys %{$self->{_del_tree}}) {
1022     next if (!$self->{_recips}{$r});
1023     $self->{_vars}{recipients_del_count}++;
1024   }
1025
1026   # blank line
1027   $_ = <I>;
1028   return(0) if (!/^$/);
1029
1030   # start reading headers
1031   while (read(I, $_, 3) == 3) {
1032     my $t = getc(I);
1033     return(0) if (!length($t));
1034     while ($t =~ /^\d$/) {
1035       $_ .= $t;
1036       $t  = getc(I);
1037     }
1038     my $hdr_flag  = $t;
1039     my $hdr_bytes = $_;
1040     $t            = getc(I);              # strip the space out of the file
1041     return(0) if (read(I, $_, $hdr_bytes) != $hdr_bytes);
1042     if ($hdr_flag ne '*') {
1043       $self->{_vars}{message_linecount} += (tr/\n//);
1044       $self->{_vars}{message_size}      += $hdr_bytes;
1045     }
1046
1047     # mark (rb)?header_ vars as existing and store raw value.  They'll be
1048     # processed further in get_var() if needed
1049     my($v,$d) = split(/:/, $_, 2);
1050     $v = "header_" . lc($v);
1051     $self->{_vars}{$v} = $self->{_vars}{"b$v"} = $self->{_vars}{"r$v"} = undef;
1052     push(@{$self->{_vars_raw}{"r$v"}{vals}}, $d);
1053     $self->{_vars_raw}{"r$v"}{type} = $hdr_flag;
1054     $self->{_vars}{message_headers_raw} .= $_;
1055   }
1056   close(I);
1057
1058   $self->{_vars}{message_body_size} =
1059       (stat($self->{_path}.'/'.$self->{_message}.'-D'))[7] - 19;
1060   if ($self->{_vars}{message_body_size} < 0) {
1061     $self->{_vars}{message_size} = 0;
1062     $self->{_vars}{message_body_missing} = 1;
1063   } else {
1064     $self->{_vars}{message_size} += $self->{_vars}{message_body_size} + 1;
1065   }
1066
1067   $self->{_vars}{message_linecount} += $self->{_vars}{body_linecount};
1068
1069   my $i = $self->{_vars}{message_size};
1070   if ($i == 0)          { $i = ""; }
1071   elsif ($i < 1024)     { $i = sprintf("%d",    $i);                    }
1072   elsif ($i < 10240)    { $i = sprintf("%.1fK", $i / 1024);             }
1073   elsif ($i < 1048576)  { $i = sprintf("%dK",   ($i+512)/1024);         }
1074   elsif ($i < 10485760) { $i = sprintf("%.1fM", $i/1048576);            }
1075   else                  { $i = sprintf("%dM",   ($i + 524288)/1048576); }
1076   $self->{_vars}{shown_message_size} = $i;
1077
1078   return(1);
1079 }
1080
1081 # mimic exim's host_extract_port function - receive a ref to a scalar,
1082 # strip it of port, return port
1083 sub _get_host_and_port {
1084   my $self = shift;
1085   my $host = shift; # scalar ref, be careful
1086
1087   if ($$host =~ /^\[([^\]]+)\](?:\:(\d+))?$/) {
1088     $$host = $1;
1089     return($2 || 0);
1090   } elsif ($$host =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?:\.(\d+))?$/) {
1091     $$host = $1;
1092     return($2 || 0);
1093   } elsif ($$host =~ /^([\d\:]+)(?:\.(\d+))?$/) {
1094     $$host = $1;
1095     return($2 || 0);
1096   }
1097   # implicit else
1098   return(0);
1099 }
1100
1101 # honoring all formatting preferences, return a scalar variable of the
1102 # information for the single message matching what exim -bp would show.
1103 # We can print later if we want.
1104 sub format_message {
1105   my $self = shift;
1106   my $o    = '';
1107   return if ($self->{_delivered});
1108
1109   # define any vars we want to print out for this message.  The requests
1110   # can be regexps, and the defined vars can change for each message, so we
1111   # have to build this list for each message
1112   my @vars = ();
1113   if (@{$self->{_show_vars}}) {
1114     my %t = ();
1115     foreach my $e (@{$self->{_show_vars}}) {
1116       foreach my $v ($self->get_matching_vars($e)) {
1117         next if ($t{$v}); $t{$v}++; push(@vars, $v);
1118       }
1119     }
1120   }
1121
1122   if ($self->{_output_idonly}) {
1123     $o .= $self->{_message};
1124     foreach my $v (@vars) { $o .= " $v='" . $self->get_var($v) . "'"; }
1125     $o .= "\n";
1126     return $o;
1127   } elsif ($self->{_output_vars_only}) {
1128     foreach my $v (@vars) { $o .= $self->get_var($v) . "\n"; }
1129     return $o;
1130   }
1131
1132   if ($self->{_output_long} || $self->{_output_flatq}) {
1133     my $i = int($self->{_vars}{message_age} / 60);
1134     if ($i > 90) {
1135       $i = int(($i+30)/60);
1136       if ($i > 72) { $o .= sprintf "%2dd ", int(($i+12)/24); }
1137       else { $o .= sprintf "%2dh ", $i; }
1138     } else { $o .= sprintf "%2dm ", $i; }
1139
1140     if ($self->{_output_flatq} && @vars) {
1141         $o .= join(';', map { "$_='".$self->get_var($_)."'" } (@vars)
1142                   );
1143     } else {
1144       $o .= sprintf "%5s", $self->{_vars}{shown_message_size};
1145     }
1146     $o .= " ";
1147   }
1148   $o .= "$self->{_message} ";
1149   $o .= "From: " if ($self->{_output_brief});
1150   $o .= "<$self->{_vars}{sender_address}>";
1151
1152   if ($self->{_output_long}) {
1153     $o .= " ($self->{_vars}{originator_login})"
1154         if ($self->{_vars}{sender_set_untrusted});
1155
1156     # XXX exim contains code here to print spool format errors
1157     $o .= " *** frozen ***" if ($self->{_vars}{deliver_freeze});
1158     $o .= "\n";
1159
1160     foreach my $v (@vars) {
1161       $o .= sprintf "  %25s = '%s'\n", $v, $self->get_var($v);
1162     }
1163
1164     foreach my $r (keys %{$self->{_recips}}) {
1165       next if ($self->{_del_tree}{$r} && $self->{_undelivered_only});
1166       $o .= sprintf "        %s %s\n", $self->{_del_tree}{$r} ? "D" : " ", $r;
1167     }
1168     if ($self->{_show_generated}) {
1169       foreach my $r (keys %{$self->{_del_tree}}) {
1170         next if ($self->{_recips}{$r});
1171         $o .= sprintf "       +D %s\n", $r;
1172       }
1173     }
1174   } elsif ($self->{_output_brief}) {
1175     my @r = ();
1176     foreach my $r (keys %{$self->{_recips}}) {
1177       next if ($self->{_del_tree}{$r});
1178       push(@r, $r);
1179     }
1180     $o .= " To: " . join(';', @r);
1181     if (scalar(@vars)) {
1182       $o .= " Vars: ".join(';',map { "$_='".$self->get_var($_)."'" } (@vars));
1183     }
1184   } elsif ($self->{_output_flatq}) {
1185     $o .= " *** frozen ***" if ($self->{_vars}{deliver_freeze});
1186     my @r = ();
1187     foreach my $r (keys %{$self->{_recips}}) {
1188       next if ($self->{_del_tree}{$r});
1189       push(@r, $r);
1190     }
1191     $o .= " " . join(' ', @r);
1192   }
1193
1194   $o .= "\n";
1195   return($o);
1196 }
1197
1198 sub print_message {
1199   my $self = shift;
1200   my $fh   = shift || \*STDOUT;
1201   return if ($self->{_delivered});
1202
1203   print $fh $self->format_message();
1204 }
1205
1206 sub dump {
1207   my $self = shift;
1208
1209   foreach my $k (sort keys %$self) {
1210     my $r = ref($self->{$k});
1211     if ($r eq 'ARRAY') {
1212       printf "%20s <<EOM\n", $k;
1213       print @{$self->{$k}}, "EOM\n";
1214     } elsif ($r eq 'HASH') {
1215       printf "%20s <<EOM\n", $k;
1216       foreach (sort keys %{$self->{$k}}) {
1217         printf "%20s %s\n", $_, $self->{$k}{$_};
1218       }
1219       print "EOM\n";
1220     } else {
1221       printf "%20s %s\n", $k, $self->{$k};
1222     }
1223   }
1224 }
1225
1226 } # BEGIN
1227
1228 sub ext_usage {
1229   if ($ARGV[0] =~ /^--help$/i) {
1230     require Config;
1231     $ENV{PATH} .= ":" unless $ENV{PATH} eq "";
1232     $ENV{PATH} = "$ENV{PATH}$Config::Config{'installscript'}";
1233     #exec("perldoc", "-F", "-U", $0) || exit 1;
1234     $< = $> = 1 if ($> == 0 || $< == 0);
1235     exec("perldoc", $0) || exit 1;
1236     # make parser happy
1237     %Config::Config = ();
1238   } elsif ($ARGV[0] =~ /^--version$/i) {
1239     print "$p_name version $p_version\n\n$p_cp\n";
1240   } else {
1241     return;
1242   }
1243
1244   exit(0);
1245 }
1246
1247 __END__
1248
1249 =head1 NAME
1250
1251 exipick - selectively display messages from an Exim queue
1252
1253 =head1 SYNOPSIS
1254
1255 exipick [<options>] [<criterion> [<criterion> ...]]
1256
1257 =head1 DESCRIPTION
1258
1259 exipick is a tool to display messages in an Exim queue.  It is very similar to exiqgrep and is, in fact, a drop in replacement for exiqgrep.  exipick allows you to select messages to be displayed using any piece of data stored in an Exim spool file.  Matching messages can be displayed in a variety of formats.
1260
1261 =head1 QUICK START
1262
1263 Delete every frozen message from queue:
1264     exipick -zi | xargs exim -Mrm
1265
1266 Show only messages which have not yet been virus scanned:
1267     exipick '$received_protocol ne virus-scanned'
1268
1269 Run the queue in a semi-random order:
1270     exipick -i --random | xargs exim -M
1271
1272 Show the count and total size of all messages which either originated from localhost or have a received protocol of 'local':
1273     exipick --or --size --bpc \
1274             '$sender_host_address eq 127.0.0.1' \
1275             '$received_protocol eq local'
1276
1277 Display all messages received on the MSA port, ordered first by the sender's email domain and then by the size of the emails:
1278     exipick --sort sender_address_domain,message_size \
1279             '$received_port == 587'
1280
1281 Display only messages whose every recipient is in the example.com domain, also listing the IP address of the sending host:
1282     exipick --show-vars sender_host_address \
1283             '$each_recipients = example.com'
1284
1285 Same as above, but show values for all defined variables starting with sender_ and the number of recipients:
1286     exipick --show-vars ^sender_,recipients_count \
1287             '$each_recipients = example.com'
1288
1289 =head1 OPTIONS
1290
1291 =over 4
1292
1293 =item --and
1294
1295 Display messages matching all criteria (default)
1296
1297 =item -b
1298
1299 Display messages in brief format (exiqgrep)
1300
1301 =item -bp
1302
1303 Display messages in standard mailq format (default)
1304
1305 =item -bpa
1306
1307 Same as -bp, show generated addresses also (exim)
1308
1309 =item -bpc
1310
1311 Show a count of matching messages (exim)
1312
1313 =item -bpr
1314
1315 Same as '-bp --unsorted' (exim)
1316
1317 =item -bpra
1318
1319 Same as '-bpr --unsorted' (exim)
1320
1321 =item -bpru
1322
1323 Same as '-bpu --unsorted' (exim)
1324
1325 =item -bpu
1326
1327 Same as -bp, but only show undelivered messages (exim)
1328
1329 =item -c
1330
1331 Show a count of matching messages (exiqgrep)
1332
1333 =item --caseful
1334
1335 Make operators involving '=' honor case
1336
1337 =item --charset
1338
1339 Override the default local character set for $header_ decoding
1340
1341 =item -f <regexp>
1342
1343 Same as '$sender_address = <regexp>' (exiqgrep)
1344
1345 =item --flatq
1346
1347 Use a single-line output format
1348
1349 =item --freeze <cache file>
1350
1351 Save queue information in an quickly retrievable format
1352
1353 =item --help
1354
1355 Display this output
1356
1357 =item -i
1358
1359 Display only the message IDs (exiqgrep)
1360
1361 =item -l
1362
1363 Same as -bp (exiqgrep)
1364
1365 =item --not
1366
1367 Negate all tests.
1368
1369 =item -o <seconds>
1370
1371 Same as '$message_age > <seconds>' (exiqgrep)
1372
1373 =item --or
1374
1375 Display messages matching any criteria
1376
1377 =item -R
1378
1379 Same as --reverse (exiqgrep)
1380
1381 =item -r <regexp>
1382
1383 Same as '$recipients = <regexp>' (exiqgrep)
1384
1385 =item --random
1386
1387 Display messages in random order
1388
1389 =item --reverse
1390
1391 Display messages in reverse order
1392
1393 =item -s <string>
1394
1395 Same as '$shown_message_size eq <string>' (exiqgrep)
1396
1397 =item --spool <path>
1398
1399 Set the path to the exim spool to use
1400
1401 =item --show-rules
1402
1403 Show the internal representation of each criterion specified
1404
1405 =item --show-tests
1406
1407 Show the result of each criterion on each message
1408
1409 =item --show-vars <variable>[,<variable>...]
1410
1411 Show the value for <variable> for each displayed message.  <variable> will be a regular expression if it begins with a circumflex.
1412
1413 =item --size
1414
1415 Show the total bytes used by each displayed message
1416
1417 =item --thaw <cache file>
1418
1419 Read queue information cached from a previous --freeze run
1420
1421 =item --sort <variable>[,<variable>...]
1422
1423 Display matching messages sorted according to <variable>
1424
1425 =item --unsorted
1426
1427 Do not apply any sorting to output
1428
1429 =item --version
1430
1431 Display the version of this command
1432
1433 =item -x
1434
1435 Same as '!$deliver_freeze' (exiqgrep)
1436
1437 =item -y
1438
1439 Same as '$message_age < <seconds>' (exiqgrep)
1440
1441 =item -z
1442
1443 Same as '$deliver_freeze' (exiqgrep)
1444
1445 =back
1446
1447 =head1 CRITERIA
1448
1449 Exipick decides which messages to display by applying a test against each message.  The rules take the general form of 'VARIABLE OPERATOR VALUE'.  For example, '$message_age > 60'.  When exipick is deciding which messages to display, it checks the $message_age variable for each message.  If a message's age is greater than 60, the message will be displayed.  If the message's age is 60 or less seconds, it will not be displayed.
1450
1451 Multiple criteria can be used.  The order they are specified does not matter.  By default all criteria must evaluate to true for a message to be displayed.  If the --or option is used, a message is displayed as long as any of the criteria evaluate to true.
1452
1453 See the VARIABLES and OPERATORS sections below for more details
1454
1455 =head1 OPERATORS
1456
1457 =over 4
1458
1459 =item BOOLEAN
1460
1461 Boolean variables are checked simply by being true or false.  There is no real operator except negation.  Examples of valid boolean tests:
1462   '$deliver_freeze'
1463   '!$deliver_freeze'
1464
1465 =item NUMERIC
1466
1467 Valid comparisons are <, <=, >, >=, ==, and !=.  Numbers can be integers or floats.  Any number in a test suffixed with d, h, m, s, M, K, or B will be mulitplied by 86400, 3600, 60, 1, 1048576, 1024, or 1 respectively.  Examples of valid numeric tests:
1468   '$message_age >= 3d'
1469   '$local_interface == 587'
1470   '$message_size < 30K'
1471
1472 =item STRING
1473
1474 The string operators are =, eq, ne, =~, and !~.  With the exception of '=', the operators all match the functionality of the like-named perl operators.  eq and ne match a string exactly.  !~, =~, and = apply a perl regular expression to a string.  The '=' operator behaves just like =~ but you are not required to place // around the regular expression.  Examples of valid string tests:
1475   '$received_protocol eq esmtp'
1476   '$sender_address = example.com'
1477   '$each_recipients =~ /^a[a-z]{2,3}@example.com$/'
1478
1479 =item NEGATION
1480
1481 There are many ways to negate tests, each having a reason for existing.  Many tests can be negated using native operators.  For instance, >1 is the opposite of <=1 and eq and ne are opposites.  In addition, each individual test can be negated by adding a ! at the beginning of the test.  For instance, '!$acl_m1 =~ /^DENY$/' is the same as '$acl_m1 !~ /^DENY$/'.  Finally, every test can be specified by using the command line argument --not.  This is functionally equivilant to adding a ! to the beginning of every test.
1482
1483 =back
1484
1485 =head1 VARIABLES
1486
1487 With a few exceptions the available variables match Exim's internal expansion variables in both name and exact contents.  There are a few notable additions and format deviations which are noted below.  Although a brief explanation is offered below, Exim's spec.txt should be consulted for full details.  It is important to remember that not every variable will be defined for every message.  For example, $sender_host_port is not defined for messages not received from a remote host.
1488
1489 Internally, all variables are represented as strings, meaning any operator will work on any variable.  This means that '$sender_host_name > 4' is a legal criterion, even if it does not produce meaningful results.  Variables in the list below are marked with a 'type' to help in choosing which types of operators make sense to use.
1490
1491   Identifiers
1492     B - Boolean variables
1493     S - String variables
1494     N - Numeric variables
1495     . - Standard variable matching Exim's content definition
1496     # - Standard variable, contents differ from Exim's definition
1497     + - Non-standard variable
1498
1499 =over 4
1500
1501 =item S . $acl_c0-$acl_c9, $acl_m0-$acl_m9
1502
1503 User definable variables.
1504
1505 =item B + $allow_unqualified_recipient
1506
1507 TRUE if unqualified recipient addresses are permitted in header lines.
1508
1509 =item B + $allow_unqualified_sender
1510
1511 TRUE if unqualified sender addresses are permitted in header lines.
1512
1513 =item S . $authenticated_id
1514
1515 Optional saved information from authenticators, or the login name of the calling process for locally submitted messages.
1516
1517 =item S . $authenticated_sender
1518
1519 The value of AUTH= param for smtp messages, or a generated value from the calling processes login and qualify domain for locally submitted messages.
1520
1521 =item S . $bheader_*, $bh_*
1522
1523 Value of the header(s) with the same name with any RFC2047 words decoded if present.  See section 11.5 of Exim's spec.txt for full details.
1524
1525 =item S + $bmi_verdicts
1526
1527 The verdict string provided by a Brightmail content scan
1528
1529 =item N . $body_linecount
1530
1531 The number of lines in the message's body.
1532
1533 =item N . $body_zerocount
1534
1535 The number of binary zero bytes in the message's body.
1536
1537 =item B + $deliver_freeze
1538
1539 TRUE if the message is currently frozen.
1540
1541 =item N + $deliver_frozen_at
1542
1543 The epoch time at which message was frozen.
1544
1545 =item B + $dont_deliver
1546
1547 TRUE if, under normal circumstances, Exim will not try to deliver the message.
1548
1549 =item S + $each_recipients
1550
1551 This is a psuedo variable which allows you to apply a test against each address in $recipients individually.  Whereas '$recipients =~ /@aol.com/' will match if any recipient address contains aol.com, '$each_recipients =~ /@aol.com$/' will only be true if every recipient matches that pattern.  Note that this obeys --and or --or being set.  Using it with --or is very similar to just matching against $recipients, but with the added benefit of being able to use anchors at the beginning and end of each recipient address.
1552
1553 =item S + $each_recipients_del
1554
1555 Like $each_recipients, but for $recipients_del
1556
1557 =item S + $each_recipients_undel
1558
1559 Like $each_recipients, but for $recipients_undel
1560
1561 =item B . $first_delivery
1562
1563 TRUE if the message has never been deferred.
1564
1565 =item S . $header_*, $h_*
1566
1567 This will always match the contents of the corresponding $bheader_* variable currently (the same behaviour Exim displays when iconv is not installed).
1568
1569 =item B . $host_lookup_deferred
1570
1571 TRUE if there was an attempt to look up the host's name from its IP address, but an error occurred that during the attempt.
1572
1573 =item B . $host_lookup_failed
1574
1575 TRUE if there was an attempt to look up the host's name from its IP address, but the attempt returned a negative result.
1576
1577 =item B + $local_error_message
1578
1579 TRUE if the message is a locally-generated error message.
1580
1581 =item S . $local_scan_data
1582
1583 The text returned by the local_scan() function when a message is received.
1584
1585 =item B . $manually_thawed
1586
1587 TRUE when the message has been manually thawed.
1588
1589 =item N . $message_age
1590
1591 The number of seconds since the message was received.
1592
1593 =item S # $message_body
1594
1595 The message's body.  Unlike Exim's variable of the same name, this variable contains the entire message body.  Newlines and nulls are replaced by spaces.
1596
1597 =item B + $message_body_missing
1598
1599 TRUE is a message's spool data file (-D file) is missing or unreadable.
1600
1601 =item N . $message_body_size
1602
1603 The size of the body in bytes.
1604
1605 =item S . $message_exim_id, $message_id
1606
1607 The unique message id that is used by Exim to identify the message.  $message_id is deprecated as of Exim 4.53.
1608
1609 =item S . $message_headers
1610
1611 A concatenation of all the header lines except for lines added by routers or transports.  RFC2047 decoding is performed
1612
1613 =item S . $message_headers_raw
1614
1615 A concatenation of all the header lines except for lines added by routers or transports.  No decoding or translation is performed.
1616
1617 =item N . $message_linecount
1618
1619 The number of lines in the entire message (body and headers).
1620
1621 =item N . $message_size
1622
1623 The size of the message in bytes.
1624
1625 =item N . $originator_gid
1626
1627 The group id under which the process that called Exim was running as when the message was received.
1628
1629 =item S + $originator_login
1630
1631 The login of the process which called Exim.
1632
1633 =item N . $originator_uid
1634
1635 The user id under which the process that called Exim was running as when the message was received.
1636
1637 =item S . $received_ip_address, $interface_address
1638
1639 The address of the local IP interface for network-originated messages.  $interface_address is deprecated as of Exim 4.64
1640
1641 =item N . $received_port, $interface_port
1642
1643 The local port number if network-originated messages.  $interface_port is deprecated as of Exim 4.64
1644
1645 =item N . $received_count
1646
1647 The number of Received: header lines in the message.
1648
1649 =item S . $received_protocol
1650
1651 The name of the protocol by which the message was received.
1652
1653 =item N . $received_time
1654
1655 The epoch time at which the message was received.
1656
1657 =item S # $recipients
1658
1659 The list of envelope recipients for a message.  Unlike Exim's version, this variable always contains every recipient of the message.  The recipients are seperated by a comma and a space.  See also $each_recipients.
1660
1661 =item N . $recipients_count
1662
1663 The number of envelope recipients for the message.
1664
1665 =item S + $recipients_del
1666
1667 The list of delivered envelope recipients for a message.  This non-standard variable is in the same format as $recipients and contains the list of already-delivered recipients including any generated addresses.  See also $each_recipients_del.
1668
1669 =item N + $recipients_del_count
1670
1671 The number of envelope recipients for the message which have already been delivered.  Note that this is the count of original recipients to which the message has been delivered.  It does not include generated addresses so it is possible that this number will be less than the number of addresses in the $recipients_del string.
1672
1673 =item S + $recipients_undel
1674
1675 The list of undelivered envelope recipients for a message.  This non-standard variable is in the same format as $recipients and contains the list of undelivered recipients.  See also $each_recipients_undel.
1676
1677 =item N + $recipients_undel_count
1678
1679 The number of envelope recipients for the message which have not yet been delivered.
1680
1681 =item S . $reply_address
1682
1683 The contents of the Reply-To: header line if one exists and it is not empty, or otherwise the contents of the From: header line.
1684
1685 =item S . $rheader_*, $rh_*
1686
1687 The value of the message's header(s) with the same name.  See section 11.5 of Exim's spec.txt for full description.
1688
1689 =item S . $sender_address
1690
1691 The sender's address that was received in the message's envelope.  For bounce messages, the value of this variable is the empty string.
1692
1693 =item S . $sender_address_domain
1694
1695 The domain part of $sender_address.
1696
1697 =item S . $sender_address_local_part
1698
1699 The local part of $sender_address.
1700
1701 =item S . $sender_helo_name
1702
1703 The HELO or EHLO value supplied for smtp or bsmtp messages.
1704
1705 =item S . $sender_host_address
1706
1707 The remote host's IP address.
1708
1709 =item S . $sender_host_authenticated
1710
1711 The name of the authenticator driver which successfully authenticated the client from which the message was received.
1712
1713 =item S . $sender_host_name
1714
1715 The remote host's name as obtained by looking up its IP address.
1716
1717 =item N . $sender_host_port
1718
1719 The port number that was used on the remote host for network-originated messages.
1720
1721 =item S . $sender_ident
1722
1723 The identification received in response to an RFC 1413 request for remote messages, the login name of the user that called Exim for locally generated messages.
1724
1725 =item B + $sender_local
1726
1727 TRUE if the message was locally generated.
1728
1729 =item B + $sender_set_untrusted
1730
1731 TRUE if the envelope sender of this message was set by an untrusted local caller.
1732
1733 =item S + $shown_message_size
1734
1735 This non-standard variable contains the formatted size string.  That is, for a message whose $message_size is 66566 bytes, $shown_message_size is 65K.
1736
1737 =item S . $smtp_active_hostname
1738
1739 The value of the active host name when the message was received, as specified by the "smtp_active_hostname" option.
1740
1741 =item S . $spam_score
1742
1743 The spam score of the message, for example '3.4' or '30.5'.  (Requires exiscan or WITH_CONTENT_SCAN)
1744
1745 =item S . $spam_score_int
1746
1747 The spam score of the message, multiplied by ten, as an integer value.  For instance '34' or '305'.  (Requires exiscan or WITH_CONTENT_SCAN)
1748
1749 =item B . $tls_certificate_verified
1750
1751 TRUE if a TLS certificate was verified when the message was received.
1752
1753 =item S . $tls_cipher
1754
1755 The cipher suite that was negotiated for encrypted SMTP connections.
1756
1757 =item S . $tls_peerdn
1758
1759 The value of the Distinguished Name of the certificate if Exim is configured to request one
1760
1761 =item N + $warning_count
1762
1763 The number of delay warnings which have been sent for this message.
1764
1765 =back
1766
1767 =head1 CONTACT
1768
1769 =over 4
1770
1771 =item EMAIL: proj-exipick@jetmore.net
1772
1773 =item HOME: jetmore.org/john/code/#exipick
1774
1775 =back
1776
1777 =cut
This page took 0.39744 seconds and 3 git commands to generate.