#
# Trend Micro FileScan API via Trophie
#
# FIXME: this code is not in sync with sophie - can't trophie
# handle directories?!?

use IO::Socket;
$|=1;


if ($trophie_sockname) {
    do_log(2,"Using Trophie");
    socket(\*sock, AF_UNIX, SOCK_STREAM, 0)
	or die "Can't open socket to Trophie: $!";
    connect(\*sock, pack_sockaddr_un $trophie_sockname)
	or die "Can't connect to Trophie: $!";

    opendir(DIR, "$TEMPDIR/parts/")
	or die "Can't open directory $TEMPDIR/parts/: $!";
    my @files = grep { -f "$TEMPDIR/parts/$_" } readdir(DIR);
    closedir(DIR) or die "Can't close directory: $!";
    chomp(@files);
    foreach my $file (@files) {
	if ($file =~ /^([A-Za-z0-9\._=+-]+)$/) {
	    $file = $1;
       	} else {
	    die "Unsafe partname $file";
	}
	# needed "\n", otherwise it won't work
	$file = "$TEMPDIR/parts/$file\n";
	
	syswrite(\*sock, $file, length($file))
	  or die "syswrite to Trophie failed: $!";
	sysread(\*sock, $output, 256)
	  or die "sysread from Trophie failed: $!";

	chomp($output);
	$output =~ s/^[A-Za-z0-9\._=+-:\/]+//g;
	do_log(2,"Trophie: $file - $output");
	last if ($output =~ m/^1/); 
    }

    close(\*sock) or die "Trophie socket close failed: $!";

    if ($output =~ m/^1/) {
	if ($output =~ m/^1:.*$/) {
	    @virusname = ($output =~ m/^1:(.*)$/g);
	}
	@virusname = (undef)  if !@virusname;  # just in case: make list nonnil
	$scanner_errors = 0;  # no errors, a virus was found
	do_virus();
    } elsif ($output == 0) {
	$scanner_errors = 0;  # no errors, no viruses
    } elsif ($output == -1) {
	do_log(0,"Virus scanner failure: Trophie - UNKNOWN STATUS (error code: $output)");
    } else {
	do_log(0,"Virus scanner failure: Trophie - OOOPS (error code: $output)");
    }
}
