Debian Codegraph @

check_email_delivery/src/check_imap_receive

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
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
493 __END__
494
495
496 =pod
497
498 =head1 NAME
499
500 check_imap_receive - connects to and searches an IMAP account for messages
501
502 =head1 SYNOPSIS
503
504 check_imap_receive -vV
505 check_imap_receive -?
506 check_imap_receive --help
507
508 =head1 OPTIONS
509
510 =over
511
512 =item --warning <seconds>
513
514 Warn if it takes longer than <seconds> to connect to the IMAP server. Default is 15 seconds.
515 Also known as: -w <seconds>
516
517 =item --critical <seconds>
518
519 Return a critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 30 seconds.
520 See also: --capture-critical <messages>
521 Also known as: -c <seconds>
522
523 =item --timeout <seconds>
524
525 Abort with critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 60 seconds.
526 The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
527 connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
528 than 30 seconds.
529 Also known as: -t <seconds>
530
531 =item --imap-check-interval <seconds>
532
533 How long to wait after searching for a matching message before searching again. Only takes effect
534 if no messages were found. Default is 5 seconds.
535
536 =item --imap-retries <number>
537
538 How many times to try searching for a matching message before giving up. If you set this to 0 then
539 messages will not be searched at all. Setting this to 1 means the plugin only tries once. Etc.
540 Default is 10 times.
541
542 =item --hostname <server>
543
544 Address or name of the IMAP server. Examples: mail.server.com, localhost, 192.168.1.100
545 Also known as: -H <server>
546
547 =item --port <number>
548
549 Service port on the IMAP server. Default is 143. If you use SSL, default is 993.
550 Also known as: -p <number>
551
552 =item --username <username>
553
554 =item --password <password>
555
556 Username and password to use when connecting to IMAP server.
557 Also known as: -U <username> -P <password>
558
559 =item --mailbox <mailbox>
560
561 Use this option to specify the mailbox to search for messages. Default is INBOX.
562 Also known as: -m <mailbox>
563
564 =item --search <string>
565
566 Use this option to filter the messages. Default is not to filter. You may (must) use this option
567 multiple times in order to create any valid IMAP search criteria. See the examples and see also
568 http://www.ietf.org/rfc/rfc2060.txt (look for section 6.4.4, the SEARCH command)
569
570 This is the way to find messages matching a given subject:
571 -s SUBJECT -s "a given subject"
572
573 You can use the following technique for any header, including Subject. To find "Header-Name: some value":
574 -s HEADER -s Header-Name -s "some value"
575
576 Modern IMAP servers that support rfc5032 extensions allow you to search for messages
577 older or younger than a number of seconds. So to find messages received in the past hour,
578 you can do:
579
580 -s YOUNGER -s 3600
581
582 Or to find messages received more than 5 minutes ago, you can do:
583
584 -s OLDER -s 300
585
586 Also known as: -s <string>
587
588 =item --download
589
590 =item --nodownload
591
592 This option causes all messages in the specified mailbox to be downloaded from the server
593 and searched locally. See --download-max if you only want to download a few messages.
594 Currently only the following RFC 2060 search criteria are supported:
595 TEXT, BODY, SUBJECT, HEADER, NOT, OR, SENTBEFORE, SENTON, SENTSINCE.
596
597 Requires Email::Simple to be installed. It is available on CPAN.
598
599 This option may be particularly useful to you if your mail server is slow to index
600 messages (like Exchange 2003), causing the plugin not to find them with IMAP SEARCH
601 even though they are in the inbox.
602
603 It's also useful if you're searching for messages that have been on the server for a
604 specified amount of time, like some minutes or hours, because the standard IMAP search
605 function only allows whole dates. For this, use the standard search keywords but you
606 can specify either just a date like in RFC 2060 or a date and a time.
607
608 If you use SENTBEFORE, SENTON, or SENTSINCE, you must have Date::Manip installed
609 on your system.
610
611
612 =item --download-max
613
614 Limits the number of messages downloaded from the server when the --download option is used.
615 Default is to download and search all messages.
616
617 =item --search-critical-min <messages>
618
619 This option will trigger a CRITICAL status if the number of messages found by the search criteria
620 is below the given number. Use in conjunction with --search.
621
622 This parameter defaults to 1 so that if no messages are found, the plugin will exit with a CRITICAL status.
623
624 If you want the original behavior where the plugin exits with a WARNING status when no messages are found,
625 set this parameter to 0.
626
627 =item --search-critical-max <messages>
628
629 This option will trigger a CRITICAL status if the number of messages found by the search criteria
630 is above the given number. Use in conjunction with --search.
631
632 This parameter defaults to -1 meaning it's disabled. If you set it to 10, the plugin will exit with
633 CRITICAL if it finds 11 messages. If you set it to 1, the plugin will exit with CRITICAL if it finds
634 any more than 1 message. If you set it to 0, the plugin will exit with CRITICAL if it finds any messages
635 at all. If you set it to -1 it will be disabled.
636
637 =item --search-warning-min <messages>
638
639 This option will trigger a WARNING status if the number of messages found by the search criteria
640 is below the given number. Use in conjunction with --search.
641
642 This parameter defaults to 1 so that if no messages are found, the plugin will exit with a WARNING status.
643
644 If you want to suppress the original behavior where the plugin exits with a WARNING status when no messages are found,
645 set this parameter to 0. When this parameter is 0, it means that you expect the mailbox not to have any messages.
646
647 =item --search-warning-max <messages>
648
649 This option will trigger a WARNING status if the number of messages found by the search criteria
650 is above the given number. Use in conjunction with --search.
651
652 This parameter defaults to -1 meaning it's disabled. If you set it to 10, the plugin will exit with
653 WARNING if it finds 11 messages. If you set it to 1, the plugin will exit with WARNING if it finds
654 any more than 1 message. If you set it to 0, the plugin will exit with WARNING if it finds any messages
655 at all. If you set it to -1 it will be disabled.
656
657 =item --capture-max <regexp>
658
659 In addition to specifying search arguments to filter the emails in the IMAP account, you can specify
660 a "capture-max" regexp argument and the eligible emails (found with search arguments)
661 will be compared to each other and the OK line will have the highest captured value.
662
663 The regexp is expected to capture a numeric value.
664
665 =item --capture-min <regexp>
666
667 In addition to specifying search arguments to filter the emails in the IMAP account, you can specify
668 a "capture-min" regexp argument and the eligible emails (found with search arguments)
669 will be compared to each other and the OK line will have the lowest captured value.
670
671 The regexp is expected to capture a numeric value.
672
673 =item --delete
674
675 =item --nodelete
676
677 Use the delete option to delete messages that matched the search criteria. This is useful for
678 preventing the mailbox from filling up with automated messages (from the check_smtp_send plugin, for example).
679 THE DELETE OPTION IS TURNED *ON* BY DEFAULT, in order to preserve compatibility with an earlier version.
680
681 Use the nodelete option to turn off the delete option.
682
683 =item --nodelete-captured
684
685 If you use both the capture-max and delete arguments, you can also use the nodelete-captured argument to specify that the email
686 with the highest captured value should not be deleted. This leaves it available for comparison the next time this plugin runs.
687
688 If you do not use the delete option, this option has no effect.
689
690 =item --ssl
691
692 =item --nossl
693
694 Enable SSL protocol. Requires IO::Socket::SSL.
695
696 Using this option automatically changes the default port from 143 to 993. You can still
697 override this from the command line using the --port option.
698
699 Use the nossl option to turn off the ssl option.
700
701 =item --ssl-ca-file
702
703 Use this to verify the server SSL certificate against a local .pem file. You'll need to
704 specify the path to the .pem file as the parameter.
705
706 You can use the imap_ssl_cert utility included in this distribution to connect to your IMAP
707 server and save its SSL certificates into your .pem file. Usage is like this:
708
709 imap_ssl_cert -H imap.server.com > ca_file.pem
710
711 Only applicable when --ssl option is enabled.
712
713 =item --template
714
715 =item --notemplate
716
717 Enable (or disable) processing of IMAP search parameters. Requires Text::Template and Date::Manip.
718
719 Use this option to apply special processing to IMAP search parameters that allows you to use the
720 results of arbitrary computations as the parameter values. For example, you can use this feature
721 to search for message received up to 4 hours ago.
722
723 Modern IMAP servers that support rfc5032 extensions allow searching with the YOUNGER and OLDER
724 criteria so a message received up to 4 hours ago is -s YOUNGER -s 14400. But if your mail server
725 doesn't support that, you could use the --template option to get similar functionality.
726
727 When you enable the --template option, each parameter you pass to the -s option is parsed by
728 Text::Template. See the Text::Template manual for more information, but in general any expression
729 written in Perl will work.
730
731 A convenience function called rfc2822dateHeader is provided to you so you can easily compute properly
732 formatted dates for use as search parameters. The rfc2822date function can take one or two
733 parameters itself: the date to format and an optional offset. To use the current time as a
734 search parameter, you can write this:
735
736 $ check_imap_receive ... --template -s HEADER -s Delivery-Date -s '{rfc2822dateHeader("now")}'
737
738 The output of {rfc2822dateHeader("now")} looks like this: Wed, 30 Sep 2009 22:44:03 -0700 and
739 is suitable for use with a date header, like HEADER Delivery-Date.
740
741 To use a time in the past relative to the current time or day, you can use a second convenience function
742 called rfc2822date and write this:
743
744 $ check_imap_receive ... --template -s SENTSINCE -s '{rfc2822date("now","-1 day")}'
745
746 The output of {rfc2822date("now","-1 day")} looks like this: 29-Sep-2009 and is suitable for use
747 with BEFORE, ON, SENTBEFORE, SENTON, SENTSINCE, and SINCE.
748
749 I have seen some email clients use a different format in the Date field,
750 like September 17, 2009 9:46:51 AM PDT. To specify an arbitrary format like this one, write this:
751
752 $ check_imap_receive ... --template -s HEADER -s Delivery-Date -s '{date("%B %e, %Y %i:%M:%S %p %Z","now","-4 hours")}'
753
754 You can use BEFORE, ON, SENTBEFORE, SENTON, SENTSINCE, or SINCE to search for messages that arrived
755 on, before, or after a given day but not on, before, or after a specific time on that day.
756
757 To search for messages that arrived on, before, or after a specific time you have to use the
758 Delivery-Date or another date field, like with -s HEADER -s Delivery-Date in the example above.
759
760 See the Date::Manip manual for more information on the allowed expressions for date and delta strings.
761
762 =item --hires
763
764 Use the Time::HiRes module to measure time, if available.
765
766 =item --verbose
767
768 Display additional information. Useful for troubleshooting. Use together with --version to see the default
769 warning and critical timeout values.
770
771 If the selected mailbox was not found, you can use verbosity level 3 (-vvv) to display a list of all
772 available mailboxes on the server.
773
774 Also known as: -v
775
776 =item --version
777
778 Display plugin version and exit.
779 Also known as: -V
780
781 =item --help
782
783 Display this documentation and exit. Does not work in the ePN version.
784 Also known as: -h
785
786 =item --usage
787
788 Display a short usage instruction and exit.
789
790 =back
791
792 =head1 EXAMPLES
793
794 =head2 Report how many emails are in the mailbox
795
796 $ check_imap_receive -H mail.server.net --username mailuser --password mailpass
797 -s ALL --nodelete
798
799 IMAP RECEIVE OK - 1 seconds, 7 found
800
801 =head2 Report the email with the highest value
802
803 Suppose your mailbox has some emails from an automated script and that a message
804 from this script typically looks like this (abbreviated):
805
806 To: [email protected]
807 From: [email protected]
808 Subject: Results of Autoscript
809 Date: Wed, 09 Nov 2005 08:30:40 -0800
810 Message-ID: <[email protected]>
811
812 Homeruns 5
813
814 And further suppose that you are interested in reporting the message that has the
815 highest number of home runs, and also to leave this message in the mailbox for future
816 checks, but remove the other matching messages with lesser values:
817
818 $ check_imap_receive -H mail.server.net --username mailuser --password mailpass
819 -s SUBJECT -s "Results of Autoscript" --capture-max "Homeruns (\d+)" --nodelete-captured
820
821 IMAP RECEIVE OK - 1 seconds, 3 found, 1 captured, 5 max, 2 deleted
822
823 =head2 Troubleshoot your search parameters
824
825 Add the --nodelete and --imap-retries=1 parameters to your command line.
826
827 =head1 EXIT CODES
828
829 Complies with the Nagios plug-in specification:
830 0 OK The plugin was able to check the service and it appeared to be functioning properly
831 1 Warning The plugin was able to check the service, but it appeared to be above some "warning" threshold or did not appear to be working properly
832 2 Critical The plugin detected that either the service was not running or it was above some "critical" threshold
833 3 Unknown Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service
834
835 =head1 NAGIOS PLUGIN NOTES
836
837 Nagios plugin reference: http://nagiosplug.sourceforge.net/developer-guidelines.html
838
839 This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
840 the path to utils.pm must be specified completely in this program and forces users to edit the source
841 code if their install location is different (if they realize this is the problem). You can view
842 the default timeout for this module by using the --verbose and --version options together. The
843 short form is -vV.
844
845 Other than that, it attempts to follow published guidelines for Nagios plugins.
846
847 =head1 SEE ALSO
848
849 http://nagios.org/
850 http://search.cpan.org/~djkernen/Mail-IMAPClient-2.2.9/IMAPClient.pod
851 http://search.cpan.org/~markov/Mail-IMAPClient-3.00/lib/Mail/IMAPClient.pod
852
853 =head1 CHANGES
854
855 Wed Oct 29 11:00:00 PST 2005
856 + version 0.1
857
858 Wed Nov 9 09:53:32 PST 2005
859 + added delete/nodelete option. deleting found messages is still default behavior.
860 + added capture-max option
861 + added nodelete-captured option
862 + added mailbox option
863 + added eval/alarm block to implement -c option
864 + now using an inline PluginReport package to generate the report
865 + copyright notice and GNU GPL
866 + version 0.2
867
868 Thu Apr 20 14:00:00 CET 2006 (by Johan Nilsson <johann (at) axis.com>)
869 + version 0.2.1
870 + added support for multiple polls of imap-server, with specified intervals
871
872 Tue Apr 24 21:17:53 PDT 2007
873 + now there is an alternate version (same but without embedded perl POD) that is compatible with the new new embedded-perl Nagios feature
874 + added patch from Benjamin Ritcey <[email protected]> for SSL support on machines that have an SSL-enabled
875 + version 0.2.3
876
877 Fri Apr 27 18:56:50 PDT 2007
878 + fixed problem that "Invalid search parameters" was not printed because of missing newline to flush it
879 + warnings and critical errors now try to append error messages received from the IMAP client
880 + changed connection error to display timeout only if timeout was the error
881 + documentation now mentions every command-line option accepted by the plugin, including abbreviations
882 + added abbreviations U for username, P for password, m for mailbox
883 + fixed bug that imap-check-interval applied even after the last try (imap-retries) when it was not necessary
884 + the IMAP expunge command is not sent unless at least one message is deleted
885 + fixed bug that the "no messages" warning was printed even if some messages were found
886 + version 0.3
887
888 Sun Oct 21 14:08:07 PDT 2007
889 + added port info to the "could not connect" error message
890 + fixed bug that occurred when using --ssl --port 143 which caused port to remain at the default 993 imap/ssl port
891 + added clarity shortcuts --search-subject and --search-header
892 + port is no longer a required option. defaults to 143 for regular IMAP and 993 for IMAP/SSL
893 + version 0.3.1
894
895 Sun Oct 21 20:41:56 PDT 2007
896 + reworked ssl support to use IO::Socket::SSL instead of the convenience method Mail::IMAPClient->Ssl (which is not included in the standard Mail::IMAPClient package)
897 + removed clarity shortcuts (bad idea, code bloat)
898 + version 0.4
899
900 Tue Dec 4 07:05:27 PST 2007
901 + added version check to _read_line workaround for SSL-related bug in Mail::IMAPClient version 2.2.9 ; newer versions fixed the bug
902 + added --usage option because the official nagios plugins have both --help and --usage
903 + added --timeout option to match the official nagios plugins
904 + fixed some minor pod formatting issues for perldoc
905 + version 0.4.1
906
907 Sat Dec 15 07:39:59 PST 2007
908 + improved compatibility with Nagios embedded perl (ePN)
909 + version 0.4.2
910
911 Mon Jan 7 21:35:23 PST 2008
912 + changed version check for Mail::IMAPClient version 2.2.9 to use string comparison le "2.2.9"
913 + fixed bug where script was dying on socket->autoflush when socket does not exist because autoflush was being called before checking the socket object
914 + version 0.4.3
915
916 Mon Feb 11 19:13:38 PST 2008
917 + fixed a bug for embedded perl version, variable "%status" will not stay shared in load_modules
918 + version 0.4.4
919
920 Mon May 26 08:33:27 PDT 2008
921 + fixed a bug for number captured, it now reflects number of messages captured instead of always returning "1"
922 + added --capture-min option to complement --capture-max
923 + added --search-critical-min to trigger a CRITICAL alert if number of messages found is less than argument, with default 1.
924 + fixed warning and critical messages to use "more than" or "less than" instead of the angle brackets, to make them more web friendly
925 + version 0.5
926
927 Wed Jul 2 14:59:05 PDT 2008
928 + fixed a bug for not finding a message after the first try, by reselecting the mailbox before each search
929 + version 0.5.1
930
931 Sat Dec 13 08:57:29 PST 2008
932 + added --download option to allow local searching of messages (useful if your server has an index that handles searching but it takes a while before new emails show up and you want immediate results), supports only the TEXT, BODY, SUBJECT, and HEADER search keys
933 + added --download-max option to set a limit on number of messages downloaded with --download
934 + version 0.6.0
935
936 Wed Sep 30 23:25:33 PDT 2009
937 + fixed --download-max option (was incorrectly looking for --download_max). currently both will work, in the future only --download-max will work
938 + added --template option to allow arbitrary substitutions for search parameters, and provided three convenience functions for working with dates
939 + added date search criteria to the --download option: SENTBEFORE, SENTON, and SENTSINCE which check the Date header and allow hours and minutes in addition to dates (whereas the IMAP standard only allows dates)
940 + added --search-critical-max to trigger a CRITICAL alert if number of messages found is more than argument, disabled by default.
941 + fixed a bug in --download --search where messages would match even though they failed the search criteria
942 + changed behavior of --download-max to look at the most recent messages first (hopefully); the IMAP protocol doesn't guarantee the order that the messages are returned but I observed that many mail servers return them in chronological order; so now --download-max reverses the order to look at the newer messages first
943 + added performance data for use with PNP4Nagios!
944 + version 0.7.0
945
946 Fri Oct 2 15:22:00 PDT 2009
947 + added --search-warning-max and --search-warning-min to trigger a WARNING alert if number of messages is more than or less than the specified number.
948 + fixed --download option not to fail with CRITICAL if mailbox is empty; now this can be configured with --search-warning-min or --search-critical-min
949 + version 0.7.1
950
951 Sat Nov 21 18:27:17 PST 2009
952 + fixed problem with using --download option on certain mail servers by turning on the IgnoreSizeErrors feature in IMAPClient
953 + added --peek option to prevent marking messages as seen
954 + version 0.7.2
955
956 Tue Jan 5 12:13:53 PST 2010
957 + added error message and exit with unknown status when an unrecognized IMAP search criteria is encountered by the --download --search option
958
959 Wed May 5 11:14:51 PDT 2010
960 + added mailbox list when mailbox is not found and verbose level 3 is on (-vvv)
961 + version 0.7.3
962
963 Tue Mar 8 18:58:14 AST 2011
964 + updated documentation for --search and --template to mention rfc5032 extensions (thanks to Stuart Henderson)
965
966 Fri May 6 08:35:09 AST 2011
967 + added --hires option to enable use of Time::Hires if available
968 + version 0.7.4
969
970 Fri Nov 11 01:51:40 AST 2011
971 + added --ssl-ca-file option to allow verifying the server certificate against a local .pem file (thanks to Alexandre Bezroutchko)
972 + added imap_ssl_cert.pl utility (not in this file) to conveniently save the server's SSL certificates into a local .pem file
973 + version 0.7.5
974
975 =head1 AUTHOR
976
977 Jonathan Buhacoff <[email protected]>
978
979 =head1 COPYRIGHT AND LICENSE
980
981 Copyright (C) 2005-2011 Jonathan Buhacoff
982
983 This program is free software; you can redistribute it and/or modify
984 it under the terms of the GNU General Public License as published by
985 the Free Software Foundation; either version 3 of the License, or
986 (at your option) any later version.
987
988 This program is distributed in the hope that it will be useful,
989 but WITHOUT ANY WARRANTY; without even the implied warranty of
990 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
991 GNU General Public License for more details.
992
993 You should have received a copy of the GNU General Public License
994 along with this program. If not, see <http://www.gnu.org/licenses/>.
995
996 http://www.gnu.org/licenses/gpl.txt
997
998 =cut
999