| 1 | package Net::Prober::imap; | ||
| 2 | $Net::Prober::imap::VERSION = '0.16'; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use base 'Net::Prober::Probe::TCP'; | ||
| 6 | |||
| 7 | sub defaults { | ||
| 8 | return { | ||
| 9 | host => undef, | ||
| 10 | port => 143, | ||
| 11 | timeout => 30, | ||
| 12 | username => undef, | ||
| 13 | password => undef, | ||
| 14 | mailbox => 'inbox', | ||
| 15 | ssl => 0, | ||
| 16 | }; | ||
| 17 | } | ||
| 18 | |||
| 19 | sub probe { | ||
| 20 | my ($self, $args) = @_; | ||
| 21 | |||
| 22 | my ($host, $port, $timeout, $username, $password, $mailbox, $ssl) = | ||
| 23 | $self->parse_args($args, qw(host port timeout username password mailbox ssl)); | ||
| 24 | |||
| 25 | my $t0 = $self->time_now(); | ||
| 26 | |||
| 27 | my $sock = $self->open_socket($args); | ||
| 28 | if (! $sock) { | ||
| 29 | return $self->probe_failed( | ||
| 30 | reason => qq{Couldn't connect to IMAP server $host:$port}, | ||
| 31 | ); | ||
| 32 | } | ||
| 33 | |||
| 34 | chomp (my $imap_banner = $self->_get_reply($sock)); | ||
| 35 | |||
| 36 | if (! $imap_banner) { | ||
| 37 | return $self->probe_failed( | ||
| 38 | reason => qq{Couldn't get IMAP banner from $host:$port} | ||
| 39 | ); | ||
| 40 | } | ||
| 41 | |||
| 42 | if ($imap_banner !~ qr{\* \s+ OK}ix) { | ||
| 43 | return $self->probe_failed( | ||
| 44 | reason => qq{Incorrect IMAP banner from $host:$port? ($imap_banner)}, | ||
| 45 | ); | ||
| 46 | } | ||
| 47 | |||
| 48 | # We can't try to login if we haven't got credentials | ||
| 49 | if ($username && $password) { | ||
| 50 | |||
| 51 | $self->_send_command($sock, login => $username, $password); | ||
| 52 | if (! $self->_get_reply($sock)) { | ||
| 53 | return $self->probe_failed( | ||
| 54 | reason => qq{Couldn't login to imap $host:$port with user $username}, | ||
| 55 | ); | ||
| 56 | } | ||
| 57 | |||
| 58 | $self->_send_command($sock, select => $mailbox); | ||
| 59 | if (! $self->_get_reply($sock, qr{OK.*Completed}i)) { | ||
| 60 | return $self->probe_failed( | ||
| 61 | reason => qq{Couldn't select mailbox $mailbox when talking to imap $host:$port} | ||
| 62 | ); | ||
| 63 | } | ||
| 64 | |||
| 65 | } | ||
| 66 | |||
| 67 | # Say goodbye | ||
| 68 | $self->_send_command($sock, 'logout'); | ||
| 69 | |||
| 70 | return $self->probe_ok( | ||
| 71 | banner => $imap_banner | ||
| 72 | ); | ||
| 73 | } | ||
| 74 | |||
| 75 | sub _send_command { | ||
| 76 | my ($self, $sock, $cmd, @args) = @_; | ||
| 77 | my $imap_cmd = sprintf ". %s %s\r\n", $cmd, join(" ", @args); | ||
| 78 | return $sock->send($imap_cmd); | ||
| 79 | } | ||
| 80 | |||
| 81 | sub _get_reply { | ||
| 82 | my ($self, $sock) = @_; | ||
| 83 | $sock->read(my $reply, 1024); | ||
| 84 | $reply =~ s{^\s+}{}; | ||
| 85 | $reply =~ s{\s+$}{}; | ||
| 86 | return $reply; | ||
| 87 | } | ||
| 88 | |||
| 89 | 1; | ||
| 90 | |||
| 91 | __END__ |