Debian Codegraph @

check_email_delivery/src/check_imap_receive_epn

raw
1 #!/usr/bin/perl
2 use strict;
3 my $VERSION = '0.7.5';
4 my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <[email protected]>';
5 my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
6 my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
7
8 # look for required modules
9 exit $status{UNKNOWN} unless load_modules(qw/Getopt::Long Mail::IMAPClient/);
10
11 BEGIN {
12 if( grep { /^--hires$/ } @ARGV ) {
13 eval "use Time::HiRes qw(time);";
14 warn "Time::HiRes not installed\n" if $@;
15 }
16 }
17
18 # get options from command line
19 Getopt::Long::Configure("bundling");
20 my $verbose = 0;
21 my $help = "";
22 my $help_usage = "";
23 my $show_version = "";
24 my $imap_server = "";
25 my $default_imap_port = "143";
26 my $default_imap_ssl_port = "993";
27 my $imap_port = "";
28 my $username = "";
29 my $password = "";
30 my $mailbox = "INBOX";
31 my @search = ();
32 my $search_critical_min = 1;
33 my $search_critical_max = -1; # -1 means disabled for this option
34 my $search_warning_min = 1;
35 my $search_warning_max = -1; # -1 means disabled for this option
36 my $capture_max = "";
37 my $capture_min = "";
38 my $delete = 1;
39 my $no_delete_captured = "";
40 my $warntime = 15;
41 my $criticaltime = 30;
42 my $timeout = 60;
43 my $interval = 5;
44 my $max_retries = 10;
45 my $download = "";
46 my $download_max = "";
47 my $peek = "";
48 my $template = "";
49 my $ssl = 0;
50 my $ssl_ca_file = "";
51 my $tls = 0;
52 my $time_hires = "";
53 my $ok;
54 $ok = Getopt::Long::GetOptions(
55 "V|version"=>\$show_version,
56 "v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
57 "w|warning=i"=>\$warntime,"c|critical=i"=>\$criticaltime,"t|timeout=i"=>\$timeout,
58 # imap settings
59 "H|hostname=s"=>\$imap_server,"p|port=i"=>\$imap_port,
60 "U|username=s"=>\$username,"P|password=s"=>\$password, "m|mailbox=s"=>\$mailbox,
61 "imap-check-interval=i"=>\$interval,"imap-retries=i"=>\$max_retries,
62 "ssl!"=>\$ssl, "ssl-ca-file=s"=>\$ssl_ca_file, "tls!"=>\$tls,
63 # search settings
64 "s|search=s"=>\@search,
65 "search-critical-min=i"=>\$search_critical_min, "search-critical-max=i"=>\$search_critical_max,
66 "search-warning-min=i"=>\$search_warning_min, "search-warning-max=i"=>\$search_warning_max,
67 "capture-max=s"=>\$capture_max, "capture-min=s"=>\$capture_min,
68 "delete!"=>\$delete, "nodelete-captured"=>\$no_delete_captured,
69 "download!"=>\$download, "download_max=i"=>\$download_max, "download-max=i"=>\$download_max,
70 "peek!"=>\$peek,
71 "template!"=>\$template,
72 # Time
73 "hires"=>\$time_hires,
74 );
75
76 if( $show_version ) {
77 print "$VERSION\n";
78 if( $verbose ) {
79 print "Default warning threshold: $warntime seconds\n";
80 print "Default critical threshold: $criticaltime seconds\n";
81 print "Default timeout: $timeout seconds\n";
82 }
83 exit $status{UNKNOWN};
84 }
85
86 if( $help ) {
87 exec "perldoc", $0 or print "Try `perldoc $0`\n";
88 exit $status{UNKNOWN};
89 }
90
91 my @required_module = ();
92 push @required_module, 'IO::Socket::SSL' if $ssl || $tls;
93 push @required_module, 'Email::Simple' if $download;
94 push @required_module, ('Text::Template','Date::Manip') if $template;
95 exit $status{UNKNOWN} unless load_modules(@required_module);
96
97 if( $help_usage
98 ||
99 ( $imap_server eq "" || $username eq "" || $password eq "" || scalar(@search)==0 )
100 ) {
101 print "Usage: $0 -H host [-p port] -U username -P password -s HEADER -s X-Nagios -s 'ID: 1234.' [-w <seconds>] [-c <seconds>] [--imap-check-interval <seconds>] [--imap-retries <tries>]\n";
102 exit $status{UNKNOWN};
103 }
104
105 # before attempting to connect to the server, check if any of the search parameters
106 # use substitution functions and make sure we can parse them first. if we can't we
107 # need to abort since the search will be meaningless.
108 if( $template ) {
109 foreach my $token (@search) {
110 my $t = Text::Template->new(TYPE=>'STRING',SOURCE=>$token,PACKAGE=>'ImapSearchTemplate');
111 $token = $t->fill_in(PREPEND=>q{package ImapSearchTemplate;});
112 #print "token: $token\n";
113 }
114 }
115
116
117 # initialize
118 my $report = new PluginReport;
119 my $time_start = time;
120
121 # connect to IMAP server
122 print "connecting to server $imap_server\n" if $verbose > 2;
123 my $imap;
124 eval {
125 local $SIG{ALRM} = sub { die "exceeded timeout $timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
126 alarm $timeout;
127
128 if( $ssl || $tls ) {
129 $imap_port = $default_imap_ssl_port unless $imap_port;
130 my %ssl_args = ();
131 if( length($ssl_ca_file) > 0 ) {
132 $ssl_args{SSL_verify_mode} = 1;
133 $ssl_args{SSL_ca_file} = $ssl_ca_file;
134 $ssl_args{SSL_verifycn_scheme} = 'imap';
135 $ssl_args{SSL_verifycn_name} = $imap_server;
136 }
137 my $socket = IO::Socket::SSL->new(PeerAddr=>"$imap_server:$imap_port", %ssl_args);
138 die IO::Socket::SSL::errstr() . " (if you get this only when using both --ssl and --ssl-ca-file, but not when using just --ssl, the server SSL certificate failed validation)" unless $socket;
139 $socket->autoflush(1);
140 $imap = Mail::IMAPClient->new(Socket=>$socket, Debug => 0 );
141 $imap->State(Mail::IMAPClient->Connected);
142 $imap->_read_line() if "$Mail::IMAPClient::VERSION" le "2.2.9"; # necessary to remove the server's "ready" line from the input buffer for old versions of Mail::IMAPClient. Using string comparison for the version check because the numeric didn't work on Darwin and for Mail::IMAPClient the next version is 2.3.0 and then 3.00 so string comparison works
143 $imap->User($username);
144 $imap->Password($password);
145 $imap->login() or die "Cannot login: $@";
146 }
147 else {
148 $imap_port = $default_imap_port unless $imap_port;
149 $imap = Mail::IMAPClient->new(Debug => 0 );
150 $imap->Server("$imap_server:$imap_port");
151 $imap->User($username);
152 $imap->Password($password);
153 $imap->connect() or die "$@";
154 }
155
156 $imap->Peek(1) if $peek;
157 $imap->Ignoresizeerrors(1);
158
159 alarm 0;
160 };
161 if( $@ ) {
162 chomp $@;
163 print "IMAP RECEIVE CRITICAL - Could not connect to $imap_server port $imap_port: $@\n";
164 exit $status{CRITICAL};
165 }
166 unless( $imap ) {
167 print "IMAP RECEIVE CRITICAL - Could not connect to $imap_server port $imap_port: $@\n";
168 exit $status{CRITICAL};
169 }
170 my $time_connected = time;
171
172 # select a mailbox
173 print "selecting mailbox $mailbox\n" if $verbose > 2;
174 unless( $imap->select($mailbox) ) {
175 print "IMAP RECEIVE CRITICAL - Could not select $mailbox: $@ $!\n";
176 if( $verbose > 2 ) {
177 print "Mailbox list:\n" . join("\n", $imap->folders) . "\n";
178 print "Mailbox separator: " . $imap->separator . "\n";
179 ##print "Special mailboxes:\n" . join("\n", map { "$_ => ".
180 }
181 $imap->logout();
182 exit $status{CRITICAL};
183 }
184
185
186 # search for messages
187 my $tries = 0;
188 my @msgs;
189 until( scalar(@msgs) != 0 || $tries >= $max_retries ) {
190 eval {
191 $imap->select( $mailbox );
192 # if download flag is on, we download recent messages and search ourselves
193 if( $download ) {
194 print "downloading messages to search\n" if $verbose > 2;
195 @msgs = download_and_search($imap,@search);
196 }
197 else {
198 print "searching on server\n" if $verbose > 2;
199 @msgs = $imap->search(@search);
200 die "Invalid search parameters: $@" if $@;
201 }
202 };
203 if( $@ ) {
204 chomp $@;
205 print "Cannot search messages: $@\n";
206 $imap->close();
207 $imap->logout();
208 exit $status{UNKNOWN};
209 }
210 $report->{found} = scalar(@msgs);
211 $tries++;
212 sleep $interval unless (scalar(@msgs) != 0 || $tries >= $max_retries);
213 }
214
215 sub download_and_search {
216 my ($imap,@search) = @_;
217 my $ims = new ImapMessageSearch;
218 $ims->querytokens(@search);
219 my @found = ();
220 @msgs = reverse $imap->messages or (); # die "Cannot list messages: $@\n"; # reversing to get descending order, which is most recent messages first! (at least on my mail servers)
221 @msgs = @msgs[0..$download_max-1] if $download_max && scalar(@msgs) > $download_max;
222 foreach my $m (@msgs) {
223 my $message = $imap->message_string($m);
224 push @found, $m if $ims->match($message);
225 }
226 return @found;
227 }
228
229
230
231 # capture data in messages
232 my $captured_max_id = "";
233 my $captured_min_id = "";
234 if( $capture_max || $capture_min ) {
235 my $max = undef;
236 my $min = undef;
237 my %captured = ();
238 for (my $i=0;$i < scalar(@msgs); $i++) {
239 my $message = $imap->message_string($msgs[$i]);
240 if( $message =~ m/$capture_max/ ) {
241 if( !defined($max) || $1 > $max ) {
242 $captured{ $i } = 1;
243 $max = $1;
244 $captured_max_id = $msgs[$i];
245 }
246 }
247 if( $message =~ m/$capture_min/ ) {
248 if( !defined($min) || $1 < $min ) {
249 $captured{ $i } = 1;
250 $min = $1;
251 $captured_min_id = $msgs[$i];
252 }
253 }
254 print $message if $verbose > 1;
255 }
256 $report->{captured} = scalar keys %captured;
257 $report->{max} = $max if defined $max;
258 $report->{min} = $min if defined $min;
259 }
260
261 # delete messages
262 if( $delete ) {
263 print "deleting matching messages\n" if $verbose > 2;
264 my $deleted = 0;
265 for (my $i=0;$i < scalar(@msgs); $i++) {
266 next if ($no_delete_captured && ($captured_max_id eq $msgs[$i]));
267 next if ($no_delete_captured && ($captured_min_id eq $msgs[$i]));
268 $imap->delete_message($msgs[$i]);
269 $deleted++;
270 }
271 $report->{deleted} = $deleted;
272 $imap->expunge() if $deleted;
273 }
274
275 # deselect the mailbox
276 $imap->close();
277
278 # disconnect from IMAP server
279 print "disconnecting from server\n" if $verbose > 2;
280 $imap->logout();
281
282 # calculate elapsed time and issue warnings
283 my $time_end = time;
284 my $elapsedtime = $time_end - $time_start;
285 $report->{seconds} = $elapsedtime;
286 $report->{found} = 0 unless defined $report->{found};
287 $report->{captured} = 0 unless defined $report->{captured};
288
289 my @warning = ();
290 my @critical = ();
291
292 push @warning, "found less than $search_warning_min" if( scalar(@msgs) < $search_warning_min );
293 push @warning, "found more than $search_warning_max" if ( $search_warning_max > -1 && scalar(@msgs) > $search_warning_max );
294 push @critical, "found less than $search_critical_min" if ( scalar(@msgs) < $search_critical_min );
295 push @critical, "found more than $search_critical_max" if ( $search_critical_max > -1 && scalar(@msgs) > $search_critical_max );
296 push @warning, "connection time more than $warntime" if( $time_connected - $time_start > $warntime );
297 push @critical, "connection time more than $criticaltime" if( $time_connected - $time_start > $criticaltime );
298
299 # print report and exit with known status
300 my $perf_data = "elapsed=".$report->{seconds}."s found=".$report->{found}."messages captured=".$report->{captured}."messages"; # TODO: need a component for safely generating valid perf data format. for notes on the format, see http://www.perfparse.de/tiki-view_faq.php?faqId=6 and http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN185
301 my $short_report = $report->text(qw/seconds found captured max min deleted/) . " | $perf_data";
302 if( scalar @critical ) {
303 my $crit_alerts = join(", ", @critical);
304 print "IMAP RECEIVE CRITICAL - $crit_alerts; $short_report\n";
305 exit $status{CRITICAL};
306 }
307 if( scalar @warning ) {
308 my $warn_alerts = join(", ", @warning);
309 print "IMAP RECEIVE WARNING - $warn_alerts; $short_report\n";
310 exit $status{WARNING};
311 }
312 print "IMAP RECEIVE OK - $short_report\n";
313 exit $status{OK};
314
315
316 # utility to load required modules. exits if unable to load one or more of the modules.
317 sub load_modules {
318 my @missing_modules = ();
319 foreach( @_ ) {
320 eval "require $_";
321 push @missing_modules, $_ if $@;
322 }
323 if( @missing_modules ) {
324 print "Missing perl modules: @missing_modules\n";
325 return 0;
326 }
327 return 1;
328 }
329
330
331 # NAME
332 # PluginReport
333 # SYNOPSIS
334 # $report = new PluginReport;
335 # $report->{label1} = "value1";
336 # $report->{label2} = "value2";
337 # print $report->text(qw/label1 label2/);
338 package PluginReport;
339
340 sub new {
341 my ($proto,%p) = @_;
342 my $class = ref($proto) || $proto;
343 my $self = bless {}, $class;
344 $self->{$_} = $p{$_} foreach keys %p;
345 return $self;
346 }
347
348 sub text {
349 my ($self,@labels) = @_;
350 my @report = map { "$self->{$_} $_" } grep { defined $self->{$_} } @labels;
351 my $text = join(", ", @report);
352 return $text;
353 }
354
355 package ImapMessageSearch;
356
357 require Email::Simple;
358
359 sub new {
360 my ($proto,%p) = @_;
361 my $class = ref($proto) || $proto;
362 my $self = bless {}, $class;
363 $self->{querystring} = [];
364 $self->{querytokens} = [];
365 $self->{queryfnlist} = [];
366 $self->{mimemessage} = undef;
367 $self->{$_} = $p{$_} foreach keys %p;
368 return $self;
369 }
370
371 sub querystring {
372 my ($self,$string) = @_;
373 $self->{querystring} = $string;
374 return $self->querytokens( parseimapsearch($string) );
375 }
376
377 sub querytokens {
378 my ($self,@tokens) = @_;
379 $self->{querytokens} = [@tokens];
380 $self->{queryfnlist} = [create_search_expressions(@tokens)];
381 return $self;
382 }
383
384 sub match {
385 my ($self,$message_string) = @_;
386 return 0 unless defined $message_string;
387 my $message_mime = Email::Simple->new($message_string);
388 return $self->matchmime($message_mime);
389 }
390
391 sub matchmime {
392 my ($self,$message_mime) = @_;
393 my $match = 1;
394 foreach my $x (@{$self->{queryfnlist}}) {
395 $match = $match && $x->($message_mime);
396 }
397 return $match;
398 }
399
400 # this should probably become its own Perl module... see also Net::IMAP::Server::Command::Search
401 sub create_search_expressions {
402 my (@search) = @_;
403 return () unless scalar(@search);
404 my $token = shift @search;
405 if( $token eq 'TEXT' ) {
406 my $value = shift @search;
407 return (sub {shift->as_string =~ /\Q$value\E/i},create_search_expressions(@search));
408 }
409 if( $token eq 'BODY' ) {
410 my $value = shift @search;
411 return (sub {shift->body =~ /\Q$value\E/i},create_search_expressions(@search));
412 }
413 if( $token eq 'SUBJECT' ) {
414 my $value = shift @search;
415 return (sub {shift->header('Subject') =~ /\Q$value\E/i},create_search_expressions(@search));
416 }
417 if( $token eq 'HEADER' ) {
418 my $name = shift @search;
419 my $value = shift @search;
420 return (sub {shift->header($name) =~ /\Q$value\E/i},create_search_expressions(@search));
421 }
422 if( $token eq 'NOT' ) {
423 my @exp = create_search_expressions(@search);
424 my $next = shift @exp;
425 return (sub { ! $next->(@_) }, @exp);
426 }
427 if( $token eq 'OR' ) {
428 my @exp = create_search_expressions(@search);
429 my $next1 = shift @exp;
430 my $next2 = shift @exp;
431 return (sub { $next1->(@_) or $next2->(@_) }, @exp);
432 }
433 if( $token eq 'SENTBEFORE' ) {
434 my $value = shift @search;
435 return (sub {datecmp(shift->header('Date'),$value) < 0},create_search_expressions(@search));
436 }
437 if( $token eq 'SENTON' ) {
438 my $value = shift @search;
439 return (sub {datecmp(shift->header('Date'),$value) == 0},create_search_expressions(@search));
440 }
441 if( $token eq 'SENTSINCE' ) {
442 my $value = shift @search;
443 return (sub {datecmp(shift->header('Date'),$value) > 0},create_search_expressions(@search));
444 }
445 return sub { die "invalid search parameter: $token" };
446 }
447
448 sub datecmp {
449 my ($date1,$date2) = @_;
450 my $parsed1 = Date::Manip::ParseDate($date1);
451 my $parsed2 = Date::Manip::ParseDate($date2);
452 my $cmp = Date::Manip::Date_Cmp($parsed1,$parsed2);
453 print " $date1 <=> $date2 -> $cmp\n";
454 return $cmp <=> 0;
455 }
456
457 package ImapSearchTemplate;
458
459 # Takes an English date specification ("now", etc) and an optional offset ("-4 hours")
460 # and returns an RFC 2822 formatted date string.
461 # see http://search.cpan.org/dist/Date-Manip/lib/Date/Manip.pod
462 sub rfc2822dateHeader {
463 my ($when,$delta) = @_;
464 $when = Date::Manip::ParseDate($when);
465 $delta = Date::Manip::ParseDateDelta($delta) if $delta;
466 my $d = $delta ? Date::Manip::DateCalc($when,$delta) : $when;
467 return Date::Manip::UnixDate($d, "%a, %d %b %Y %H:%M:%S %z");
468 }
469
470 sub rfc2822date {
471 my ($when,$delta) = @_;
472 $when = Date::Manip::ParseDate($when);
473 $delta = Date::Manip::ParseDateDelta($delta) if $delta;
474 my $d = $delta ? Date::Manip::DateCalc($when,$delta) : $when;
475 return Date::Manip::UnixDate($d, "%d-%b-%Y");
476 }
477
478 # alias for 2822 ... RFC 822 is an older version and specifies 2-digit years, but we ignore that for now.
479 sub rfc822dateHeader { return rfc2822dateHeader(@_); }
480 sub rfc822date { return rfc2822date(@_); }
481
482 sub date {
483 my ($format,$when,$delta) = @_;
484 $when = Date::Manip::ParseDate($when);
485 $delta = Date::Manip::ParseDateDelta($delta) if $delta;
486 my $d = $delta ? Date::Manip::DateCalc($when,$delta) : $when;
487 return Date::Manip::UnixDate($d, $format);
488 }
489
490 package main;
491 1;
492