package Yaa::Daemon::Protocol::LMTP;

# inherit everything from Yaa::Daemon and 
@ISA = qw(
	Yaa::Daemon
);

# standard modules
use strict;
use Yaa::Daemon;

# specific modules
use Net::Server::Mail::LMTP;

sub new {
	my $proto = shift;
	my $args = shift;
	my $class = ref($proto) || $proto;
	my $self = Yaa::Daemon->new();
	
	$self->{error_sleep_time} = 5;

	bless($self, $class);
	return $self;
}

# Net::Server Hook
sub process_request {
	my ($self) = @_;

	# initialize Net::Server::Mail::LMTP object and configure it
	unless (defined $self->{_lmtp}) {
		$self->{_lmtp} = Net::Server::Mail::LMTP->new(
			error_sleep_time => $self->{error_sleep_time}
		);
		
		unless (defined $self->{_lmtp}) {
			$self->{error} = "LMTP server initialization failed.";
			$self->_logger("Error: " . $self->{error});
			return 0;
		}

		# RCPT callback. Any recipient is sufficient.
		$self->{_lmtp}->set_callback(RCPT => sub { return 1; });
	
		# DATA command. fetch message and process it.
		$self->{_lmtp}->set_callback(DATA => sub {
				my ($session, $data) = @_;
				
				# clear request parameters
				$self->clearRequest();

				# remove <> chars from sender address
				my $addr = $session->get_sender();
				$addr =~ s/[<>]//g;
				$self->{_lmtp_sender} = $addr;
				
				# remove <> chars from recipient addresses
				foreach ($session->get_recipients()) {
					$_ =~ s/[<>]//g;
					push(@{$self->{_lmtp_recipients}}, $_);
				}
				
				# process message utilizing Yaa!
				my $result = $self->processMessage($data);
			
				# send success or failure status back to LMTP client
				my $msgid = $self->{_msgid};
				$self->{_msgid} = undef;
				if ($result) {
					return(1, 250, "Message successfully queued as " . $msgid);
				} else {
					return(0, 450, "Error queueing message with id " . $msgid);
				}
			}
		);
	}
	
	# process connection
	return $self->{_lmtp}->process;
}

sub clearRequest {
	my ($self) = @_;
	$self->{_sender} = undef;
	@{$self->{_lmtp_recipients}} = undef;
}

sub _getProtocolSender {
	my ($self) = @_;
	$self->_logger("Protocol sender address: " . $self->{_lmtp_sender});
	return $self->{_lmtp_sender};
}

sub _getProtocolRecipients {
	my ($self) = @_;
	$self->_logger("Protocol recipient address(es): " . join(", ", @{$self->{_lmtp_recipients}}));
	return @{$self->{_lmtp_recipients}};
}

1;

=head1 SEE ALSO

perldoc Yaa
perldoc Yaa::Daemon

=cut

=head1 AUTHOR

Branko F. Gracnar <bfg@frost.ath.cx>
http://frost.ath.cx/~bfg

=cut

=head1 LICENSE

This software is released under BSD-style license. If you like this software, send me a nice postcard from somewhere to the snail mail address published on my website.

=cut

