#!/usr/local/bin/perl

use MIME::Decoder;

# :set tabstop=3 in vi ;)

# get seperator
while(<>){
	chop;
	last if(/^$/); # only want to read header
	if(/^Content-Type:\s+multipart\/mixed;/i){
		my $line = <>;
		if($line =~ /boundary="([^"]+)"/i){
			$boundary = $1;
		}
	}
}

exit unless(defined($boundary));

foreach my $foo ('mime','plain'){
	# skip
	while(<>){
		last if(/^--${boundary}/);
	}
}

while(<>){
	chop;
	last if(/^--${boundary}/ || /^$/);
	if(/^Content-Transfer-Encoding:\s+(.+)/i){
		$encoding = $1;
	}elsif(/filename="([^"]+)"/i){
		$filename = $1;
		# no lamerz
		if($filename =~ /\.\./){
			$filename =~ s/\.\.//g;
		}elsif($filename =~ /\//){
			$filename =~ s#/##g;
		}
	}
}

if(defined($filename) && defined($encoding)){
	open(T, ">/tmp/$filename.tmp") || die "cannot write to /tmp/$filename.tmp: $!\n";
	while(<>){
		# the encoded attachment
		last if(/^--${boundary}--/ || /^$/);
		print T;
	}
	close T;
	if(-s "/tmp/$filename.tmp"){
		if(supported MIME::Decoder "$encoding"){
			open(F, ">/tmp/$filename") || die "cannot write to /tmp/$filename: $!\n";
			open(T, "/tmp/$filename.tmp") || die "cannot open /tmp/$filename.tmp: $!\n";
			my $decode = new MIME::Decoder "$encoding";
			$decode->decode(\*T, \*F) || die "cant decode: $!\n";
			close F;
			close T;
		}else{
			warn "Found attachment, but I am too primitive to decode it..\n";
		}
	}
	unlink("/tmp/$filename.tmp");
}
