Installed the latest exipick (20041110) from John Jetmore, with changes
[exim.git] / src / src / exipick.src
1 #!PERL_COMMAND
2 # $Cambridge: exim/src/src/exipick.src,v 1.2 2004/11/12 12:01:52 ph10 Exp $
3
4 # This variable should be set by the building process to Exim's spool directory.
5 my $spool = 'SPOOL_DIRECTORY';
6
7 use strict;
8 use Getopt::Long;
9
10 my($p_name) = $0 =~ m|/?([^/]+)$|;
11 my $p_version = "20041110.0";
12 my $p_usage = "Usage: $p_name [--help|--version] (see --help for details)";
13 my $p_cp = <<EOM;
14 Copyright (c) 2003-2004 John Jetmore <jj33\@pobox.com>
15
16 This program is free software; you can redistribute it and/or modify
17 it under the terms of the GNU General Public License as published by
18 the Free Software Foundation; either version 2 of the License, or
19 (at your option) any later version.
20
21 This program is distributed in the hope that it will be useful,
22 but WITHOUT ANY WARRANTY; without even the implied warranty of
23 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 GNU General Public License for more details.
25
26 You should have received a copy of the GNU General Public License
27 along with this program; if not, write to the Free Software
28 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 EOM
30 ext_usage(); # before we do anything else, check for --help
31
32 Getopt::Long::Configure("bundling_override");
33 GetOptions(
34 'spool:s' => \$G::spool, # exim spool dir
35 'bp' => \$G::mailq_bp, # List the queue (noop - default)
36 'bpa' => \$G::mailq_bpa, # ... with generated address as well
37 'bpc' => \$G::mailq_bpc, # ... but just show a count of messages
38 'bpr' => \$G::mailq_bpr, # ... do not sort
39 'bpra' => \$G::mailq_bpra, # ... with generated addresses, unsorted
40 'bpru' => \$G::mailq_bpru, # ... only undelivered addresses, unsorted
41 'bpu' => \$G::mailq_bpu, # ... only undelivered addresses
42 'and' => \$G::and, # 'and' the criteria (default)
43 'or' => \$G::or, # 'or' the criteria
44 'f:s' => \$G::qgrep_f, # from regexp
45 'r:s' => \$G::qgrep_r, # recipient regexp
46 #'s:s' => \$G::qgrep_s, # match against size field
47 'y:s' => \$G::qgrep_y, # message younger than (secs)
48 'o:s' => \$G::qgrep_o, # message older than (secs)
49 'z' => \$G::qgrep_z, # frozen only
50 'x' => \$G::qgrep_x, # non-frozen only
51 'c' => \$G::qgrep_c, # display match count
52 'l' => \$G::qgrep_l, # long format (default)
53 'i' => \$G::qgrep_i, # message ids only
54 'b' => \$G::qgrep_b, # brief format
55 'flatq' => \$G::flatq, # brief format
56 'caseful' => \$G::caseful, # in '=' criteria, respect case
57 'caseless'=> \$G::caseless, # ...ignore case (default)
58 'show-vars:s' => \$G::show_vars, # display the contents of these vars
59 'show-rules' => \$G::show_rules # display compiled match rules
60 ) || exit(1);
61
62 push(@ARGV, "\$sender_address =~ /$G::qgrep_f/") if ($G::qgrep_f);
63 push(@ARGV, "\$recipients =~ /$G::qgrep_r/") if ($G::qgrep_r);
64 push(@ARGV, "\$message_age < $G::qgrep_y") if ($G::qgrep_y);
65 push(@ARGV, "\$message_age > $G::qgrep_o") if ($G::qgrep_o);
66 push(@ARGV, "\$deliver_freeze") if ($G::qgrep_z);
67 push(@ARGV, "!\$deliver_freeze") if ($G::qgrep_x);
68 $G::mailq_bp = $G::mailq_bp; # shut up -w
69 $G::and = $G::and; # shut up -w
70 $G::msg_ids = {};
71 $G::caseless = $G::caseful ? 0 : 1; # nocase by default, case if both used
72 $spool = $G::spool if ($G::spool);
73 my $count_only = 1 if ($G::mailq_bpc || $G::qgrep_c);
74 my $unsorted = 1 if ($G::mailq_bpr || $G::mailq_bpra || $G::mailq_bpru);
75 my $msg = get_all_msgs($spool, $unsorted);
76 my $crit = process_criteria(\@ARGV);
77 my $e = Exim::SpoolFile->new();
78 my $tcount = 0 if ($count_only);
79 my $mcount = 0 if ($count_only);
80 $e->set_spool($spool);
81 $e->set_undelivered_only(1) if ($G::mailq_bpru || $G::mailq_bpu);
82 $e->set_show_generated(1) if ($G::mailq_bpa || $G::mailq_bpra);
83 $e->output_long() if ($G::qgrep_l);
84 $e->output_idonly() if ($G::qgrep_i);
85 $e->output_brief() if ($G::qgrep_b);
86 $e->output_flatq() if ($G::flatq);
87 $e->set_show_vars($G::show_vars) if ($G::show_vars);
88
89 MSG:
90 foreach my $m (@$msg) {
91 next if (scalar(keys(%$G::msg_ids)) && !$G::or
92 && !$G::msg_ids->{$m->{message}});
93 if (!$e->parse_message($m->{message})) {
94 warn "Couldn't parse $m->{message}: ".$e->error()."\n";
95 next(MSG);
96 }
97 $tcount++;
98 my $match = 0;
99 CRITERIA:
100 foreach my $c (@$crit) {
101 my $var = $e->get_var($c->{var});
102 my $ret = eval($c->{cmp});
103 if ($@) {
104 print STDERR "Error in eval '$c->{cmp}': $@\n";
105 next(MSG);
106 } elsif ($ret) {
107 $match = 1;
108 if ($G::or) { last(CRITERIA); }
109 else { next(CRITERIA); }
110 } else { # no match
111 if ($G::or) { next(CRITERIA); }
112 else { next(MSG); }
113 }
114 }
115 next(MSG) if (scalar(@$crit) > 0 && !$match);
116
117 if ($count_only) {
118 $mcount++;
119 } else {
120 $e->print_message(\*STDOUT);
121 }
122 }
123
124 if ($G::mailq_bpc) {
125 print "$tcount\n";
126 } elsif ($G::qgrep_c) {
127 print "$mcount matches out of $tcount messages\n";
128 }
129
130 exit;
131
132 sub process_criteria {
133 my $a = shift;
134 my @c = ();
135 my $e = 0;
136
137 foreach (@$a) {
138 foreach my $t ('@') { s/$t/\\$t/g; } # '$'
139 if (/^(.*?)\s+(<=|>=|==|!=|<|>)\s+(.*)$/) {
140 #print STDERR "found as integer\n";
141 my $v = $1; my $o = $2; my $n = $3;
142 if ($n =~ /^([\d\.]+)M$/) { $n = $1 * 1024 * 1024; }
143 elsif ($n =~ /^([\d\.]+)K$/) { $n = $1 * 1024; }
144 elsif ($n =~ /^([\d\.]+)B?$/) { $n = $1; }
145 elsif ($n =~ /^([\d\.]+)d$/) { $n = $1 * 60 * 60 * 24; }
146 elsif ($n =~ /^([\d\.]+)h$/) { $n = $1 * 60 * 60; }
147 elsif ($n =~ /^([\d\.]+)m$/) { $n = $1 * 60; }
148 elsif ($n =~ /^([\d\.]+)s?$/) { $n = $1; }
149 else {
150 print STDERR "Expression $_ did not parse: numeric comparison with ",
151 "non-number\n";
152 $e = 1;
153 next;
154 }
155 push(@c, { var => lc($v), cmp => "(\$var $o $n) ? 1 : 0" });
156 } elsif (/^(.*?)\s+(=~|!~)\s+(.*)$/) {
157 #print STDERR "found as string regexp\n";
158 push(@c, { var => lc($1), cmp => "(\"\$var\" $2 $3) ? 1 : 0" });
159 } elsif (/^(.*?)\s+=\s+(.*)$/) {
160 #print STDERR "found as bare string regexp\n";
161 my $case = $G::caseful ? '' : 'i';
162 push(@c, { var => lc($1), cmp => "(\"\$var\" =~ /$2/$case) ? 1 : 0" });
163 } elsif (/^(.*?)\s+(eq|ne)\s+(.*)$/) {
164 #print STDERR "found as string cmp\n";
165 my $var = lc($1); my $op = $2; my $val = $3;
166 push(@c, { var => $var, cmp => "(\"\$var\" $op \"$val\") ? 1 : 0" });
167 if ($var eq 'message_id' && $op eq "eq") {
168 #print STDERR "short circuit @c[-1]->{cmp} $val\n";
169 $G::msg_ids->{$val} = 1;
170 }
171 } elsif (/^(!)?(\S+)$/) {
172 #print STDERR "found as boolean\n";
173 push(@c, { var => lc($2), cmp => "($1\$var) ? 1 : 0" });
174 } else {
175 print STDERR "Expression $_ did not parse\n";
176 $e = 1;
177 }
178 }
179
180 exit(1) if ($e);
181
182 if ($G::show_rules) { foreach (@c) { print "$_->{var}\t$_->{cmp}\n"; } }
183
184 return(\@c);
185 }
186
187 sub get_all_msgs {
188 my $d = shift() . '/input';
189 my $u = shift;
190 my @m = ();
191
192 opendir(D, "$d") || die "Couldn't opendir $d: $!\n";
193 foreach my $e (grep !/^\./, readdir(D)) {
194 if ($e =~ /^[a-zA-Z0-9]$/) {
195 opendir(DD, "$d/$e") || next;
196 foreach my $f (grep !/^\./, readdir(DD)) {
197 push(@m, { message => $1, path => "$e/$1" }) if ($f =~ /^(.{16})-H$/);
198 }
199 closedir(DD);
200 } elsif ($e =~ /^(.{16})-H$/) {
201 push(@m, { message => $1, path => $1 });
202 }
203 }
204 closedir(D);
205
206 return($u ? \@m : [ sort { $a->{message} cmp $b->{message} } @m ]);
207 }
208
209 BEGIN {
210
211 package Exim::SpoolFile;
212
213 $Exim::SpoolFile::ACL_C_MAX = 10;
214 #$Exim::SpoolFile::ACL_M_MAX = 10;
215
216 sub new {
217 my $class = shift;
218 my $self = {};
219 bless($self, $class);
220
221 $self->{_spool_dir} = '';
222 $self->{_undelivered_only} = 0;
223 $self->{_show_generated} = 0;
224 $self->{_output_long} = 1;
225 $self->{_output_idonly} = 0;
226 $self->{_output_brief} = 0;
227 $self->{_output_flatq} = 0;
228 $self->{_show_vars} = {};
229
230 $self->_reset();
231 return($self);
232 }
233
234 sub output_long {
235 my $self = shift;
236
237 $self->{_output_long} = 1;
238 $self->{_output_idonly} = 0;
239 $self->{_output_brief} = 0;
240 $self->{_output_flatq} = 0;
241 }
242
243 sub output_idonly {
244 my $self = shift;
245
246 $self->{_output_long} = 0;
247 $self->{_output_idonly} = 1;
248 $self->{_output_brief} = 0;
249 $self->{_output_flatq} = 0;
250 }
251
252 sub output_brief {
253 my $self = shift;
254
255 $self->{_output_long} = 0;
256 $self->{_output_idonly} = 0;
257 $self->{_output_brief} = 1;
258 $self->{_output_flatq} = 0;
259 }
260
261 sub output_flatq {
262 my $self = shift;
263
264 $self->{_output_long} = 0;
265 $self->{_output_idonly} = 0;
266 $self->{_output_brief} = 0;
267 $self->{_output_flatq} = 1;
268 }
269
270 sub set_show_vars {
271 my $self = shift;
272 my $s = shift;
273
274 foreach my $v (split(/\s*,\s*/, $s)) {
275 $self->{_show_vars}{$v}++;
276 }
277 }
278
279 sub set_show_generated {
280 my $self = shift;
281 $self->{_show_generated} = shift;
282 }
283
284 sub set_undelivered_only {
285 my $self = shift;
286 $self->{_undelivered_only} = shift;
287 }
288
289 sub error {
290 my $self = shift;
291 return $self->{_error};
292 }
293
294 sub _error {
295 my $self = shift;
296 $self->{_error} = shift;
297 return(undef);
298 }
299
300 sub _reset {
301 my $self = shift;
302
303 $self->{_error} = '';
304 $self->{_delivered} = 0;
305 $self->{_message} = '';
306 $self->{_path} = '';
307 $self->{_vars} = {};
308
309 $self->{_numrecips} = 0;
310 $self->{_udel_tree} = {};
311 $self->{_del_tree} = {};
312 $self->{_recips} = {};
313
314 return($self);
315 }
316
317 sub parse_message {
318 my $self = shift;
319
320 $self->_reset();
321 $self->{_message} = shift || return(0);
322 return(0) if (!$self->{_spool_dir});
323 if (!$self->_find_path()) {
324 # assume the message was delivered from under us and ignore
325 $self->{_delivered} = 1;
326 return(1);
327 }
328 $self->_parse_header() || return(0);
329
330 return(1);
331 }
332
333 sub _find_path {
334 my $self = shift;
335
336 return(0) if (!$self->{_message});
337 return(0) if (!$self->{_spool_dir});
338
339 foreach my $f ('', substr($self->{_message}, 5, 1).'/') {
340 if (-f $self->{_spool_dir} . "/input/$f" . $self->{_message} . '-H') {
341 $self->{_path} = $self->{_spool_dir} . "/input/$f";
342 return(1);
343 }
344 }
345 return(0);
346 }
347
348 sub set_spool {
349 my $self = shift;
350 $self->{_spool_dir} = shift;
351 }
352
353 # accepts a variable with or without leading '$' or trailing ':'
354 sub get_var {
355 my $self = shift;
356 my $var = shift;
357
358 $var =~ s/^\$//;
359 $var =~ s/:$//;
360
361 $self->_parse_body()
362 if ($var eq 'message_body' && !$self->{_vars}{message_body});
363
364 return $self->{_vars}{$var};
365 }
366
367 sub _parse_body {
368 my $self = shift;
369 my $f = $self->{_path} . '/' . $self->{_message} . '-D';
370
371 open(I, "<$f") || return($self->_error("Couldn't open $f: $!"));
372 chomp($_ = <I>);
373 return(0) if ($self->{_message}.'-D' ne $_);
374
375 $self->{_vars}{message_body} = join('', <I>);
376 close(I);
377 $self->{_vars}{message_body} =~ s/\n/ /g;
378 $self->{_vars}{message_body} =~ s/\000/ /g;
379 return(1);
380 }
381
382 sub _parse_header {
383 my $self = shift;
384 my $f = $self->{_path} . '/' . $self->{_message} . '-H';
385
386 open(I, "<$f") || return($self->_error("Couldn't open $f: $!"));
387 chomp($_ = <I>);
388 return(0) if ($self->{_message}.'-H' ne $_);
389 $self->{_vars}{message_id} = $self->{_message};
390
391 # line 2
392 chomp($_ = <I>);
393 return(0) if (!/^(\S+)\s(\d+)\s(\d+)$/);
394 $self->{_vars}{originator_login} = $1;
395 $self->{_vars}{originator_uid} = $2;
396 $self->{_vars}{originator_gid} = $3;
397
398 # line 3
399 chomp($_ = <I>);
400 return(0) if (!/^<(.*)>$/);
401 $self->{_vars}{sender_address} = $1;
402 $self->{_vars}{sender_address_domain} = $1;
403 $self->{_vars}{sender_address_local_part} = $1;
404 $self->{_vars}{sender_address_domain} =~ s/^.*\@//;
405 $self->{_vars}{sender_address_local_part} =~ s/^(.*)\@.*$/$1/;
406
407 # line 4
408 chomp($_ = <I>);
409 return(0) if (!/^(\d+)\s(\d+)$/);
410 $self->{_vars}{received_time} = $1;
411 $self->{_vars}{warning_count} = $2;
412 $self->{_vars}{message_age} = time() - $self->{_vars}{received_time};
413
414 while (<I>) {
415 chomp();
416 if (/^(-\S+)\s*(.*$)/) {
417 my $tag = $1;
418 my $arg = $2;
419 if ($tag eq '-acl') {
420 my $t;
421 return(0) if ($arg !~ /^(\d+)\s(\d+)$/);
422 if ($1 < $Exim::SpoolFile::ACL_C_MAX) {
423 $t = "acl_c$1";
424 } else {
425 $t = "acl_m" . ($1 - $Exim::SpoolFile::ACL_C_MAX);
426 }
427 read(I, $self->{_vars}{$t}, $2+1) || return(0);
428 chomp($self->{_vars}{$t});
429 } elsif ($tag eq '-local') {
430 $self->{_vars}{sender_local} = 1;
431 } elsif ($tag eq '-localerror') {
432 $self->{_vars}{local_error_message} = 1;
433 } elsif ($tag eq '-local_scan') {
434 $self->{_vars}{local_scan_data} = $arg;
435 } elsif ($tag eq '-host_lookup_failed') {
436 $self->{_vars}{host_lookup_failed} = 1;
437 } elsif ($tag eq '-body_linecount') {
438 $self->{_vars}{body_linecount} = $arg;
439 } elsif ($tag eq '-frozen') {
440 $self->{_vars}{deliver_freeze} = 1;
441 $self->{_vars}{deliver_frozen_at} = $arg;
442 } elsif ($tag eq '-deliver_firsttime') {
443 $self->{_vars}{deliver_firsttime} = 1;
444 $self->{_vars}{first_delivery} = 1;
445 } elsif ($tag eq '-manual_thaw') {
446 $self->{_vars}{deliver_manual_thaw} = 1;
447 $self->{_vars}{manually_thawed} = 1;
448 } elsif ($tag eq '-auth_id') {
449 $self->{_vars}{authenticated_id} = $arg;
450 } elsif ($tag eq '-auth_sender') {
451 $self->{_vars}{authenticated_sender} = $arg;
452 } elsif ($tag eq '-sender_set_untrusted') {
453 $self->{_vars}{sender_set_untrusted} = 1;
454 } elsif ($tag eq '-tls_certificate_verified') {
455 $self->{_vars}{tls_certificate_verified} = 1;
456 } elsif ($tag eq '-tls_cipher') {
457 $self->{_vars}{tls_cipher} = $arg;
458 } elsif ($tag eq '-tls_peerdn') {
459 $self->{_vars}{tls_peerdn} = $arg;
460 } elsif ($tag eq '-host_address') {
461 $self->{_vars}{sender_host_port} = $self->_get_host_and_port(\$arg);
462 $self->{_vars}{sender_host_address} = $arg;
463 } elsif ($tag eq '-interface_address') {
464 $self->{_vars}{interface_port} = $self->_get_host_and_port(\$arg);
465 $self->{_vars}{interface_address} = $arg;
466 } elsif ($tag eq '-host_auth') {
467 $self->{_vars}{sender_host_authenticated} = $arg;
468 } elsif ($tag eq '-host_name') {
469 $self->{_vars}{sender_host_name} = $arg;
470 } elsif ($tag eq '-helo_name') {
471 $self->{_vars}{sender_helo_name} = $arg;
472 } elsif ($tag eq '-ident') {
473 $self->{_vars}{sender_ident} = $arg;
474 } elsif ($tag eq '-received_protocol') {
475 $self->{_vars}{received_protocol} = $arg;
476 } elsif ($tag eq '-N') {
477 $self->{_vars}{dont_deliver} = 1;
478 } elsif ($tag eq '-body_zerocount') {
479 $self->{_vars}{body_zerocount} = $arg;
480 } elsif ($tag eq '-allow_unqualified_recipient') {
481 $self->{_vars}{allow_unqualified_recipient} = 1;
482 } elsif ($tag eq '-allow_unqualified_sender') {
483 $self->{_vars}{allow_unqualified_sender} = 1;
484 } else {
485 # unrecognized tag, save it for reference
486 $self->{$tag} = $arg;
487 }
488 } else {
489 last;
490 }
491 }
492
493 # when we drop out of the while loop, we have the first line of the
494 # delivered tree in $_
495 do {
496 if ($_ eq 'XX') {
497 ; # noop
498 } elsif ($_ =~ s/^[YN][YN]\s+//) {
499 $self->{_del_tree}{$_} = 1;
500 } else {
501 return(0);
502 }
503 chomp($_ = <I>);
504 } while ($_ !~ /^\d+$/);
505
506 $self->{_numrecips} = $_;
507 $self->{_vars}{recipients_count} = $self->{_numrecips};
508 for (my $i = 0; $i < $self->{_numrecips}; $i++) {
509 chomp($_ = <I>);
510 return(0) if (/^$/);
511 my $addr = '';
512 if (/^(.*)\s\d+,(\d+),\d+$/) {
513 #print STDERR "exim3 type (untested): $_\n";
514 $self->{_recips}{$1} = { pno => $2 };
515 $addr = $1;
516 } elsif (/^(.*)\s(\d+)$/) {
517 #print STDERR "exim4 original type (untested): $_\n";
518 $self->{_recips}{$1} = { pno => $2 };
519 $addr = $1;
520 } elsif (/^(.*)\s(.*)\s(\d+),(\d+)#1$/) {
521 #print STDERR "exim4 new type #1 (untested): $_\n";
522 return($self->_error("incorrect format: $_")) if (length($2) != $3);
523 $self->{_recips}{$1} = { pno => $4, errors_to => $2 };
524 $addr = $1;
525 } elsif (/^.*#(\d+)$/) {
526 print STDERR "exim4 #$1 style (unimplemented): $_\n";
527 $self->_error("exim4 #$1 style (unimplemented): $_");
528 } else {
529 #print STDERR "default type: $_\n";
530 $self->{_recips}{$_} = {};
531 $addr = $_;
532 }
533 $self->{_udel_tree}{$addr} = 1 if (!$self->{_del_tree}{$addr});
534 }
535 $self->{_vars}{recipients} = join(', ', keys(%{$self->{_recips}}));
536 $self->{_vars}{recipients_del} = join(', ', keys(%{$self->{_del_tree}}));
537 $self->{_vars}{recipients_undel} = join(', ', keys(%{$self->{_udel_tree}}));
538 $self->{_vars}{recipients_undel_count} = scalar(keys(%{$self->{_udel_tree}}));
539 $self->{_vars}{recipients_del_count} = 0;
540 foreach my $r (keys %{$self->{_del_tree}}) {
541 next if (!$self->{_recips}{$r});
542 $self->{_vars}{recipients_del_count}++;
543 }
544
545 # blank line
546 $_ = <I>;
547 return(0) if (!/^$/);
548
549 # start reading headers
550 while (read(I, $_, 3) == 3) {
551 my $t = getc(I);
552 return(0) if (!length($t));
553 while ($t =~ /^\d$/) {
554 $_ .= $t;
555 $t = getc(I);
556 }
557 # ok, right here $t contains the header flag and $_ contains the number of
558 # bytes to read. If we ever use the header flag, grab it here.
559 $self->{_vars}{message_size} += $_ if ($t ne '*');
560 $t = getc(I); # strip the space out of the file
561 my $bytes = $_;
562 return(0) if (read(I, $_, $bytes) != $bytes);
563 chomp(); # may regret this later
564 # build the $header_ variable, following exim's rules (sort of)
565 if (/^([^ :]+):(.*)$/s) {
566 my $v = "header_" . lc($1);
567 my $d = $2;
568 $d =~ s/^\s*//;
569 $d =~ s/\s*$//;
570 $self->{_vars}{$v} .= (defined($self->{_vars}{$v}) ? "\n" : '') . $d;
571 $self->{_vars}{received_count}++ if ($v eq 'header_received');
572 }
573 # push header onto $message_headers var, following exim's rules
574 $self->{_vars}{message_headers} .=
575 (defined($self->{_vars}{message_headers}) ? "\n" : '') . $_;
576 }
577 close(I);
578
579 if (length($self->{_vars}{"header_reply-to"}) > 0) {
580 $self->{_vars}{reply_address} = $self->{_vars}{"header_reply-to"};
581 } else {
582 $self->{_vars}{reply_address} = $self->{_vars}{header_from};
583 }
584
585 $self->{_vars}{message_body_size} =
586 (stat($self->{_path}.'/'.$self->{_message}.'-D'))[7] - 19;
587 if ($self->{_vars}{message_body_size} < 0) {
588 $self->{_vars}{message_size} = 0;
589 } else {
590 $self->{_vars}{message_size} += $self->{_vars}{message_body_size} + 1;
591 }
592
593 return(1);
594 }
595
596 # mimic exim's host_extract_port function - receive a ref to a scalar,
597 # strip it of port, return port
598 sub _get_host_and_port {
599 my $self = shift;
600 my $host = shift; # scalar ref, be careful
601
602 if ($$host =~ /^\[([^\]]+)\](?:\:(\d+))?$/) {
603 $$host = $1;
604 return($2 || 0);
605 } elsif ($$host =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?:\.(\d+))?$/) {
606 $$host = $1;
607 return($2 || 0);
608 } elsif ($$host =~ /^([\d\:]+)(?:\.(\d+))?$/) {
609 $$host = $1;
610 return($2 || 0);
611 }
612 # implicit else
613 return(0);
614 }
615
616 sub print_message {
617 my $self = shift;
618 my $fh = shift || \*STDOUT;
619 return if ($self->{_delivered});
620
621 if ($self->{_output_idonly}) {
622 print $fh $self->{_message}, "\n";
623 return;
624 }
625
626 if ($self->{_output_long} || $self->{_output_flatq}) {
627 my $i = int($self->{_vars}{message_age} / 60);
628 if ($i > 90) {
629 $i = int(($i+30)/60);
630 if ($i > 72) { printf $fh "%2dd ", int(($i+12)/24); }
631 else { printf $fh "%2dh ", $i; }
632 } else { printf $fh "%2dm ", $i; }
633
634 $i = $self->{_vars}{message_size};
635 if ($i == 0) { $i = " "; }
636 elsif ($i < 1024) { $i = sprintf("%5d", $i); }
637 elsif ($i < 10*1024) { $i = sprintf("%4.1fK", $i / 1024); }
638 elsif ($i < 1024*1024) { $i = sprintf("%4dK", ($i+512)/1024); }
639 elsif ($i < 10*1024*1024) { $i = sprintf("%4.1fM", $i/(1024*1024)); }
640 else { $i = sprintf("%4dM", ($i + 512 * 1024)/(1024*1024)); }
641 print $fh "$i ";
642 }
643 print $fh "$self->{_message} ";
644 print $fh "From: " if ($self->{_output_brief});
645 print $fh "<$self->{_vars}{sender_address}>";
646
647 if ($self->{_output_long}) {
648 print $fh " ($self->{_vars}{originator_login})"
649 if ($self->{_vars}{sender_set_untrusted});
650
651 # XXX exim contains code here to print spool format errors
652 print $fh " *** frozen ***" if ($self->{_vars}{deliver_freeze});
653 print $fh "\n";
654
655 foreach my $v (keys(%{$self->{_show_vars}})) {
656 printf $fh " %25s = '%s'\n", $v, $self->get_var($v);
657 }
658
659 foreach my $r (keys %{$self->{_recips}}) {
660 next if ($self->{_del_tree}{$r} && $self->{_undelivered_only});
661 printf $fh " %s %s\n", $self->{_del_tree}{$r} ? "D" : " ", $r;
662 }
663 if ($self->{_show_generated}) {
664 foreach my $r (keys %{$self->{_del_tree}}) {
665 next if ($self->{_recips}{$r});
666 printf $fh " +D %s\n", $r;
667 }
668 }
669 } elsif ($self->{_output_brief}) {
670 my @r = ();
671 foreach my $r (keys %{$self->{_recips}}) {
672 next if ($self->{_del_tree}{$r});
673 push(@r, $r);
674 }
675 print $fh " To: ", join(';', @r);
676 } elsif ($self->{_output_flatq}) {
677 print $fh " *** frozen ***" if ($self->{_vars}{deliver_freeze});
678 my @r = ();
679 foreach my $r (keys %{$self->{_recips}}) {
680 next if ($self->{_del_tree}{$r});
681 push(@r, $r);
682 }
683 print $fh " ", join(' ', @r);
684 }
685
686 print $fh "\n";
687 }
688
689 sub dump {
690 my $self = shift;
691
692 foreach my $k (sort keys %$self) {
693 my $r = ref($self->{$k});
694 if ($r eq 'ARRAY') {
695 printf "%20s <<EOM\n", $k;
696 print @{$self->{$k}}, "EOM\n";
697 } elsif ($r eq 'HASH') {
698 printf "%20s <<EOM\n", $k;
699 foreach (sort keys %{$self->{$k}}) {
700 printf "%20s %s\n", $_, $self->{$k}{$_};
701 }
702 print "EOM\n";
703 } else {
704 printf "%20s %s\n", $k, $self->{$k};
705 }
706 }
707 }
708
709 } # BEGIN
710
711 sub ext_usage {
712 if ($ARGV[0] =~ /^--help$/i) {
713 require Config;
714 $ENV{PATH} .= ":" unless $ENV{PATH} eq "";
715 $ENV{PATH} = "$ENV{PATH}$Config::Config{'installscript'}";
716 #exec("perldoc", "-F", "-U", $0) || exit 1;
717 $< = $> = 1 if ($> == 0 || $< == 0);
718 exec("perldoc", $0) || exit 1;
719 # make parser happy
720 %Config::Config = ();
721 } elsif ($ARGV[0] =~ /^--version$/i) {
722 print "$p_name version $p_version\n\n$p_cp\n";
723 } else {
724 return;
725 }
726
727 exit(0);
728 }
729
730 __END__
731
732 =head1 NAME
733
734 exipick - display messages from Exim queue based on a variety of criteria
735
736 =head1 USAGE
737
738 exipick [--help|--version] | [-spool <spool>] [-and|-or] [-bp|-bpa|-bpc|-bpr|-bpra|-bpru|-bpu] [<criterion> [<criterion> ...]]
739
740 =head1 DESCRIPTION
741
742 exipick is designed to display the contents of a Exim mail spool based on user-specified criteria. It is designed to mimic the output of 'exim -bp' (or any of the other -bp* options) and Exim's spec.txt should be used to learn more about the exact format of the output. The criteria are formed by creating comparisons against characteristics of the messages, for instance message_size, sender_helo_name, or message_headers.
743
744 =head1 OPTIONS
745
746 =over 4
747
748 =item -spool
749
750 The path to exim's spool directory. In general usage you should set the $spool variable in the script to your site's main spool directory, but this option is useful for alternate installs, or installs on NFS servers, etc.
751
752 =item -and
753
754 A message will be displayed only if it matches all of the specified criteria. This is the default.
755
756 =item -or
757
758 A message will be displayed if it matches any of the specified criteria.
759
760 =item --caseful
761
762 By default criteria using the '=' operator are caseless. Specifying this option make them respect case.
763
764 =item The -bp* options all control how much information is displayed and in what manner. They all match the functionality of the options of the same name in Exim. Briefly:
765
766 =item -bp display the matching messages in 'mailq' format.
767
768 =item -bpa ... with generated addresses as well.
769
770 =item -bpc ... just show a count of messages.
771
772 =item -bpr ... do not sort.
773
774 =item -bpra ... with generated addresses, unsorted.
775
776 =item -bpru ... only undelivered addresses, unsorted.
777
778 =item -bpu ... only undelivered addresses.
779
780 Please see Exim's spec.txt for details on the format and information displayed with each option.
781
782 =item The following options are included for compatibility with the 'exiqgrep' utility:
783
784 =item -f <regexp> Same as '$sender_address = <regexp>'
785
786 =item -r <regexp> Same as '$recipients = <regexp>'
787
788 =item -y <seconds> Same as '$message_age < <seconds>'
789
790 =item -o <seconds> Same as '$message_age > <seconds>'
791
792 =item -z Same as '$deliver_freeze'
793
794 =item -x Same as '!$deliver_freeze'
795
796 =item -c Display count of matches only
797
798 =item -l Display in long format (default)
799
800 =item -i Display message IDs only
801
802 =item -b Display brief format only
803
804 Please see the 'exiqgrep' documentation for more details on the behaviour and output format produced by these options
805
806 =item <criterion>
807
808 The criteria are used to determine whether or not a given message should be displayed. The criteria are built using variables containing information about the individual messages (see VARIABLES section for list and descriptions of available variables). Each criterion is evaluated for each message in the spool and if all (by default) criteria match or (if -or option is specified) any criterion matches, the message is displayed. See VARIABLE TYPES for explanation of types of variables and the evaluations that can be performed on them and EXAMPLES section for complete examples.
809
810 The format of a criterion is explained in detail below, but a key point to make is that the variable being compared must always be on the left side of the comparison.
811
812 If no criteria are provided all messages in the queue are displayed (in this case the output of exipick should be identical to the output of 'exim -bp')
813
814 =item --help
815
816 This screen.
817
818 =item --version
819
820 Version info.
821
822 =back
823
824 =head1 VARIABLE TYPES
825
826 Although there are variable types defined, they are defined only by the type of data that gets put into them. They are internally typeless. Because of this it is perfectly legal to perform a numeric comparison against a string variable, although the results will probably be meaningless.
827
828 =over 4
829
830 =item NUMERIC
831
832 Variable of the numeric type can be of integer or float. Valid comparisons are <, <=, >, >=, ==, and !=.
833
834 The numbers specified in the criteria can have a suffix of d, h, m, s, M, K, or B, in which case the number will be mulitplied by 86400, 3600, 60, 1, 1048576, 1024, or 1 respectively. These suffixes are case sensitive. While these are obviously designed to aid in date and size calculations, they are not restricted to variables of their respective types.
835
836 =item BOOLEAN
837
838 Variables of the boolean type are very easy to use in criteria. The format is either the variable by itself or the variable negated with a ! sign. For instance, 'deliver_freeze' matches if the message in question is frozen, '!deliver_freeze' matches if message is not frozen.
839
840 =item STRING
841
842 String variables are basically defined as those that are neither numeric nor boolean and can contain any data. There are several types of comparisons that can be made against string variables. With the exception of '=', the operators all match the functionality of the like-named perl operators.
843
844 The simplest form is a bare string regular expression, represented by the operator '='. The value used for the comparison will be evaluated as a regular expression and can be as simple or as complex as desired. For instance 'sender_helo_name = example' on the simple end or 'sender_helo_name = ^aol\.com$' on the more complex end. This comparison is caseless by default. See --caseful option.
845
846 Slightly more complex is the string comparison with the operators 'eq' and 'ne' for equal and not equal, respectively. 'sender_helo_name eq hotmail.com' is true for messages with the exact helo string "hotmail.com", while 'sender_helo_name ne hotmail.com' is true for any message any helo string other than hotmail.com.
847
848 The most complex and the most flexible format are straight regular expressions with the operators =~ and !~. The value in the criteria is expected to be a correctly formatted perl regular expression B<including the regexp delimiters (usually //)>. The criterion 'sender_helo_name !~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/' matches for any message which does not have an IP address for its helo string.
849
850 =back
851
852 =head1 VARIABLES
853
854 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.
855
856 In the list below, '.' denotes standard messages with contents matching Exim's variable, '#' denotes standard variables with non-standard contents, and '+' denotes a non-standard variable.
857
858 =head2 Boolean variables
859
860 =over 4
861
862 =item + allow_unqualified_recipient
863
864 TRUE if unqualified recipient addresses are permitted in header lines.
865
866 =item + allow_unqualified_sender
867
868 TRUE if unqualified sender addresses are permitted in header lines.
869
870 =item + deliver_freeze
871
872 TRUE if the message is frozen.
873
874 =item . first_delivery
875
876 TRUE if the message has not been deferred.
877
878 =item . manually_thawed
879
880 TRUE when the message has been manually thawed.
881
882 =item + dont_deliver
883
884 TRUE if, under normal circumstances, Exim will not try to deliver the message.
885
886 =item . host_lookup_failed
887
888 TRUE if there was an attempt to look up the host's name from its IP address, but the attempt failed.
889
890 =item + local_error_message
891
892 TRUE if the message is a locally-generated error message.
893
894 =item + sender_local
895
896 TRUE if the message was locally generated.
897
898 =item + sender_set_untrusted
899
900 TRUE if the envelope sender of this message was set by an untrusted local caller.
901
902 =item . tls_certificate_verified
903
904 TRUE if a TLS certificate was verified when the message was received.
905
906 =back
907
908 =head2 Numeric variables
909
910 =over 4
911
912 =item . body_linecount
913
914 The number of lines in the message's body.
915
916 =item . body_zerocount
917
918 The number of binary zero bytes in the message's body.
919
920 =item + deliver_frozen_at
921
922 The epoch time at which message was frozen.
923
924 =item . interface_port
925
926 The local port number if network-originated messages.
927
928 =item . message_age
929
930 The number of seconds since the message was received.
931
932 =item . message_body_size
933
934 The size of the body in bytes.
935
936 =item . message_size
937
938 The size of the message in bytes.
939
940 =item . originator_gid
941
942 The group id under which the process that called Exim was running as when the message was received.
943
944 =item . originator_uid
945
946 The user id under which the process that called Exim was running as when the message was received.
947
948 =item . received_count
949
950 The number of Received: header lines in the message.
951
952 =item + received_time
953
954 The epoch time at which the message was received.
955
956 =item . recipients_count
957
958 The number of envelope recipients for the message.
959
960 =item + recipients_del_count
961
962 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.
963
964 =item + recipients_undel_count
965
966 The number of envelope recipients for the message which have not yet been delivered.
967
968 =item . sender_host_port
969
970 The port number that was used on the remote host for network-originated messages.
971
972 =item + warning_count
973
974 The number of delay warnings which have been sent for this message.
975
976 =back
977
978 =head2 String variables
979
980 =over 4
981
982 =item . acl_c0-acl_c9, acl_m0-acl_m9
983
984 User definable variables.
985
986 =item . authenticated_id
987
988 Optional saved information from authenticators, or the login name of the calling process for locally submitted messages.
989
990 =item . authenticated_sender
991
992 The value of AUTH= param for smtp messages, or a generated value from the calling processes login and qualify domain for locally submitted messages.
993
994 =item # header_*
995
996 The value of the same named message header, for example header_to or header_reply-to. These variables are really closer to Exim's rheader_* variables, with the exception that leading and trailing space is removed.
997
998 =item . interface_address
999
1000 The address of the local IP interface for network-originated messages.
1001
1002 =item . local_scan_data
1003
1004 The text returned by the local_scan() function when a message is received.
1005
1006 =item # message_body
1007
1008 The message's body. Unlike Exim's variable of the same name, this variable contains the entire message body. The logic behind this is that the message body is not read unless it is specifically referenced, so under normal circumstances it is not a penalty, but when you need the entire body you need the entire body. Like Exim's copy, newlines and nulls are replaced by spaces.
1009
1010 =item . message_headers
1011
1012 A concatenation of all the header lines except for lines added by routers or transports.
1013
1014 =item . message_id
1015
1016 The unique message id that is used by Exim to identify the message.
1017
1018 =item + originator_login
1019
1020 The login of the process which called Exim.
1021
1022 =item . received_protocol
1023
1024 The name of the protocol by which the message was received.
1025
1026 =item # recipients
1027
1028 The list of envelope recipients for a message. Unlike Exim's version, this variable always contains every envelope recipient of the message. The recipients are separated by a comma and a space.
1029
1030 =item + recipients_del
1031
1032 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.
1033
1034 =item + recipients_undel
1035
1036 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.
1037
1038 =item . reply_address
1039
1040 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.
1041
1042 =item . sender_address
1043
1044 The sender's address that was received in the message's envelope. For bounce messages, the value of this variable is the empty string.
1045
1046 =item . sender_address_domain
1047
1048 The domain part of sender_address.
1049
1050 =item . sender_address_local_part
1051
1052 The local part of sender_address.
1053
1054 =item . sender_helo_name
1055
1056 The HELO or EHLO value supplied for smtp or bsmtp messages.
1057
1058 =item . sender_host_address
1059
1060 The remote host's IP address.
1061
1062 =item . sender_host_authenticated
1063
1064 The name of the authenticator driver which successfully authenticated the client from which the message was received.
1065
1066 =item . sender_host_name
1067
1068 The remote host's name as obtained by looking up its IP address.
1069
1070 =item . sender_ident
1071
1072 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.
1073
1074 =item . tls_cipher
1075
1076 The cipher suite that was negotiated for encrypted SMTP connections.
1077
1078 =item . tls_peerdn
1079
1080 The value of the Distinguished Name of the certificate if Exim is configured to request one.
1081
1082 =back
1083
1084 =head1 EXAMPLES
1085
1086 =over 4
1087
1088 =item exipick 'deliver_freeze'
1089
1090 Display only frozen messages.
1091
1092 =item exipick 'received_protocol eq asmtp' 'message_age < 20m'
1093
1094 Display only messages wich were delivered over an authenticated smtp session in the last 20 minutes.
1095
1096 =item exipick -bpc 'message_size > 200K'
1097
1098 Display a count of messages in the queue which are over 200 kilobytes in size.
1099
1100 =item exipick -or 'sender_helo_name =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/' 'sender_helo_name = _'
1101
1102 Display message which have a HELO string which either is an IP address or contains an underscore.
1103
1104 =back
1105
1106 =head1 REQUIREMENTS
1107
1108 None that I know of, except an Exim installation. Your life will also be a lot easier if you set $spool at the top of the script to your install's spool directory.
1109
1110 =head1 ACKNOWLEDGEMENTS
1111
1112 Although I conceived of the concept for this program independently, the name 'exipick' was taken from the Exim WishList and was suggested by Jeffrey Goldberg.
1113
1114 Thank you to Philip Hazel for writing Exim. Of course this program exists because of Exim, but more specifically the message parsing code is based on Exim's and some of this documentation was copy/pasted from Exim's.
1115
1116 =head1 CONTACT
1117
1118 =over 4
1119
1120 =item EMAIL: proj-exipick@jetmore.net
1121
1122 =item HOME: jetmore.org/john/code/#exipick
1123
1124 =back
1125
1126 =cut