package Lire::FTP::IISFtp;

use vars qw/ @ISA /;

use Lire::DlfSchema;
use Lire::W3CExtendedLog;
use Lire::Logger;

use base qw/Lire::W3CExtendedLog/;

sub new {
    my $class = shift;
    my $self = $class->SUPER::new( @_ );

    # Use URI type to parse method which looks like [54]created
    $self->{'identifier2type'}{'method'} = 'uri';
    $self->{'ftp_sessions'} = {};

    $self;
}

sub build_parser {
    my ( $self ) = shift;
    $self->SUPER::build_parser( @_ );

    my @fields = split ' ', $self->{'fields'};
    my %fields = map { $_ => 1 } @fields;

    # We absolutely need those fields
    die "missing cs-method field\n"
      unless exists $fields{'cs-method'};
    die "missing cs-uri-stem field\n"
      unless exists $fields{'cs-uri-stem'};

	$self->{'ftp_dlf_converter'} = sub {
        my ($process, $line) = @_;
		my $w3c = $self->{'w3c_parser'}->($line);

        my($sess_id, $command) = $w3c->{'cs-method'} =~ /^\[(\d+)\](.*)$/
          or die "failed to parse cs-method: $w3c->{'cs-method'}\n";

        my $user = $self->{'ftp_sessions'}{$sess_id};

        if($command eq 'USER') {
            $self->{'ftp_sessions'}{$sess_id} = $w3c->{'cs-uri-stem'};
        } elsif($command eq 'QUIT' || $command eq 'closed') {
            delete $self->{'ftp_sessions'}{$sess_id};
        } elsif($command eq 'created' || $command eq 'sent') {
            my %dlf = (
				'time' => $w3c->{'lire_time'},
				'username' => $w3c->{'cs-username'} || $user,
				'filename' => $w3c->{'cs-uri-stem'},
				'file_size' => $w3c->{'cs-bytes'},
            );
            $dlf{'transfer_time'} = $w3c->{'time-taken'} + 0
                if exists $w3c->{'time-taken'};

            $dlf{'direction'} = $command eq 'created' ? 'upload' : 'download';

            if($w3c->{'c-dns'} && $w3c->{'c-dns'} ne '-') {
                $dlf{'remote_host'} = $w3c->{'c-dns'};
            } else {
                $dlf{'remote_host'} = $w3c->{'c-ip'};
            }

            return $process->write_dlf('ftp', \%dlf);
        } elsif($command eq 'PASS') {
            # Nothing to do here;
        } else {
            lr_warn("unknown FTP command: $command");
        }
        return;
    }
}


package Lire::FTP::IisFtpDlfConverter;

use strict;

use Lire::DlfConverter;
use Carp;

use base qw/Lire::DlfConverter/;

sub new {
    my $proto = shift;
    bless {}, (ref $proto || $proto);
}

sub name { 'iis_ftp' }
sub title { 'Microsoft IIS ftp log' }
sub description { '<para>Microsoft IIS ftp log</para>' }
sub schemas { qw/ftp/ }

sub handle_log_lines { 1 }

sub init_dlf_converter {
    my ($self, $process) = @_;
	$self->{'parser'} = new Lire::FTP::IISFtp;
	$self->{'body'} = 0;
}

sub process_log_line {
    my ($self, $process, $line) = @_;

    #
    # skip invalid log entries
    #

    local $_ = $line;

	if(/^#/) {
		$self->{'parser'}->parse_directive($_);
	} else {
		if(!$self->{'body'}) {
			if(defined $self->{'parser'}{'fields'} && defined $self->{'parser'}{'version'}) {
				$self->{'body'} = 1;
			} else {
				croak "invalid Microsoft FTP IIS Log File: must start with Version and Fields directives";
			}
		}

		$self->{'parser'}{'ftp_dlf_converter'}->($process, $_);
	}
}

sub finish_conversion {
    my ($self, $process) = @_;

    my @fields = qw/time user remote_host action ftp query
        success result connection_id/;

    foreach my $query (@{$self->{'queries'}}) {
        my %dlf = map { $_ => $query->{$_} } @fields;
        $process->write_dlf('ftp', \%dlf);
    }
}

1; # nag nag.

__END__

=pod

=head1 NAME

Lire::FTP::IisFtpDlfConverter - convert Microsoft Ftp Server Logs into DLF

=head1 SYNOPSIS

B<Lire::FTP::IisFtpDlfConverter>

=head1 DESCRIPTION

Lire::FTP::IisFtpDlfConverter converts Microsoft FTP Server log files into the
FTP DLF format. Those log files are in a format which is based on the W3C
Extended Log Format.

To have the maximum information in you reports, we suggests that you log
the following fields:

time, time-taken, c-dns or c-ip, cs-uri-stem, sc-bytes

We also support the cs-uri field.

Other fields will be ignored.

=head1 LIMITATIONS

The converter doesn't handle aggregation (record with count field) and
will refuse to process those logs. Also it doesn't support changing
the fields in the middle of the log file. This means that all records
in the log file must have the same format.

=head1 AUTHORS

Francis J. Lacoste <flacoste@logreport.org>,
Wessel Dankers <wsl@logreport.org>

=head1 VERSION

$Id: IisFtpDlfConverter.pm,v 1.7 2006/07/23 13:16:35 vanbaal Exp $

=head1 COPYRIGHT

Copyright (C) 2001-2003 Stichting LogReport Foundation LogReport@LogReport.org

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program (see COPYING); if not, check with
http://www.gnu.org/copyleft/gpl.html.

=cut

# Local Variables:
# mode: cperl
# End:
