Safari Cookie Whitelist Filter in Perl

Martin Dittus · 2005-07-25 · code, osx, tools · write a comment

Since Tiger I've been pretty satisfied with Safari, and there are fewer reasons to install third party plugins than ever. Yeah I could use Firefox's keyword search, but after having one too many browser crashes due to a SIMBL plugin running amok I figured I could just as well live without it. The only thing that has really been missing was a working Cookie whitelist. There is Cookies Eater, another SIMBL plugin; but that hasn't been updated for the current Safari version yet. And even if it had been, I'm not so sure that SIMBL is the best way to enhance applications and still maintain a stable system.

So after one too many times of hand-deleting unwanted cookies I figured I could just as well write a script for it; after all, Safari's cookies are stored in a .plist file, which basically is XML. And then I found the hardly documented but functional Mac::PropertyList. After some time of figuring out the specifics it turned out it's remarkably simple.

So here it is: cookiefilter.pl -- simply edit the @valid_domains array to reflect your personal preferences, make sure that the script finds Mac::PropertyList, and close Safari before you execute it. De rien.

#!/usr/bin/perl -w

# Simple whitelist filter for Safari cookies: removes all 
# those cookies where the domain name is not in the whitelist.
#
# Edit the @valid_domains array before you execute this; and 
# Safari should obviously be closed.
#
# No warranties. Backup first.
#
# Martin Dittus, http://dekstop.de/
# Last change: 2005-07-25

use strict;
use warnings;

use lib './lib';
use Mac::PropertyList;

my @valid_domains = (
	"flickr.com", "musikcube.com", "del.icio.us"
);

my $filename = glob("~/Library/Cookies/Cookies.plist");
my $in = Mac::PropertyList::parse_plist_file( $filename );
my $out = Mac::PropertyList::array->new();
my $count = 0;

foreach my $entry (@{$in}) {
	my %cookie = %{$entry};
	my $domain = $cookie{"Domain"}->value();
	my $match = 0;
	foreach my $item (@valid_domains) {
		$match = 1 if ($domain =~ m/$item/i);
		last if ($match == 1);
	}
	if ($match == 1) {
		push @{$out}, $entry;
		print "Keeping cookie for $domain\n";		
	}
	else {	
		print "Removing cookie for $domain\n";
		$count++;
	}
}

open(FILE,"> $filename") or die $!; 
print FILE Mac::PropertyList::plist_as_string($out);
close(FILE);

print "$count cookies removed.\n";

Next article:

Previous article:

Recent articles:

Comments

Comments are closed. You can contact me instead.