#!/usr/bin/perl -w
use strict;

##############################################################################
# - each arg is a qmail-smtpd logfile
# - output is written to oldname.log
# - all usernames + passwords will be scrambled
#
# ctime:   2004-06-13
# mtime:   2004-06-13
# version: 0.1 / rel 03
##############################################################################
my @pids;

foreach my $logfile (@ARGV) {
	open(LOG, $logfile);
	open(OUT, ">$logfile.log");
	while (<LOG>) {
		chomp;

		# 1. these lines are skipped, sensitive data
		if (/checkpasswd:/)  { next; }
		if (/checkqpasswd:/) { next; }
		if (/multicheckpw:/) { next; }
	        if (/SASL we got/) { next; }

		# 2. replace $USER from <user@host>
		if (/<.+@.+>/) {
			my $user;
			my $host;

			s/<.+@.+>/%MAIL%/g; # spaceholder
			($user,$host) = split(/@/, $&);
			$user =~ s/[=\w+]/x/g;
			s/%MAIL%/$user\@$host/g; # replace spaceholder
		}

		my $line=$_;

		# 3. replace usernames + passwords from logins
		# 3.1: 'S: 334 PDI...' -> 'S: 334 xxx...'
		# 3.2: save the pid, for 'C: dGVzdEBtY21pbGs...' -> 'C: xxxxxxxxxxxxxxx...'
		if (/S: 334/) {
			my $ts;
			my $pid;
			my $data;
			($ts,$pid,$data) = split(/:/);

			my $P = $pid;
			$P =~ s/[\D]*//g; # extract pid value
			push @pids, $P; # add it to the array, which we look for l8er

			my $x1; my $x2;
			($x1,$x2) = split(/334 /);
			$x2 =~ s/[=\w+]/x/g;
			$line = $x1 . "334 " . $x2;
		}

		# 3.3: scramble saved pids
		foreach my $P (@pids) {
			if (/$P C:/) {
				my $x1; my $x2;
				($x1,$x2) = split(/C:/);
				$x2 =~ s/[=\w+]/x/g;
				$line = $x1 . "C:" . $x2;
				pop @pids;
			}
		}

		# 4. C: AUTH PLAIN xxx
		if (/C: AUTH PLAIN/) {
			my $x1; my $x2;
			($x1,$x2) = split(/C: AUTH PLAIN/);
			$x2 =~ s/[=\w+]/x/g;
			$line = $x1 . "C: AUTH PLAIN" . $x2;
		}

		print OUT "$line\n";

	}
	close (LOG);
	close (OUT);
}
