Annotation of src/usr.bin/skey/skeyprune.pl, Revision 1.1
1.1 ! millert 1: #!/usr/bin/perl
! 2: #
! 3: # Prune commented out and crufty entries from skeykeys
! 4: # Usage: skeyprune [days]
! 5: #
! 6: # Todd C. Miller <Todd.Miller@courtesan.com>
! 7: # $OpenBSD: $
! 8:
! 9: # We need to be able convert to time_t
! 10: require 'timelocal.pl';
! 11:
! 12: # Keep out the stupid
! 13: die "Only root may run $0.\n" if $>;
! 14: die "Usage: $0 [days]\n" if $#ARGC > 0;
! 15:
! 16: # Pathnames
! 17: $keyfile = '/etc/skeykeys';
! 18: $temp = "$keyfile.tmp$$";
! 19:
! 20: # Quick mapping of month name -> number
! 21: %months = ('Jan', 0, 'Feb', 1, 'Mar', 2, 'Apr', 3, 'May', 4, 'Jun', 5,
! 22: 'Jul', 6, 'Aug', 7, 'Sep', 8, 'Oct', 9, 'Nov', 10, 'Dec', 11);
! 23:
! 24: # Remove entries that haven't been modified in this many days.
! 25: $days_old = $ARGV[0] || -1;
! 26:
! 27: # Open current key file
! 28: open(OLD, $keyfile) || die "$0: Can't open $keyfile: $!\n";
! 29:
! 30: # Safely open temp file
! 31: umask(077);
! 32: unlink($temp);
! 33: open(NEW, ">$temp") || die "$0: Can't open tempfile $temp: $!\n";
! 34:
! 35: # We need to be extra speedy to close the window where someone can hose us.
! 36: setpriority(0, 0, -4);
! 37:
! 38: while (<OLD>) {
! 39: # Ignore commented out entries
! 40: if ( ! /^#[^\s#]+\s+(MD[0-9]+\s+)?[0-9]+\s+[A-z0-9_-]+\s+[a-f0-9]+\s+(Jan|Feb|Mar|Apr|May|Ju[nl]|Aug|Sep|Oct|Nov|Dec)\s+[0-9]+,\s*[0-9]+\s+[0-9]+:[0-9]+:[0-9]+$/ ) {
! 41: /((Jan|Feb|Mar|Apr|May|Ju[nl]|Aug|Sep|Oct|Nov|Dec)\s+[0-9]+,\s*[0-9]+\s+[0-9]+:[0-9]+:[0-9]+)$/;
! 42:
! 43: # Prune out old entries if asked to
! 44: if ($days_old > 0) {
! 45: # build up time based on date string
! 46: @date = split(/[\s,:]/, $1);
! 47: $sec = $date[5];
! 48: $min = $date[4];
! 49: $hours = $date[3];
! 50: $mday = $date[1] - 1;
! 51: $mon = $months{$date[0]};
! 52: $year = $date[2] - 1900;
! 53:
! 54: $now = time();
! 55: $then = &timelocal($sec,$min,$hours,$mday,$mon,$year);
! 56: if (($now - $then) / (60 * 60 * 24) - 1 <= $days_old) {
! 57: print NEW $_ || do {
! 58: warn "Can't write to $temp: $!\n";
! 59: unlink($temp);
! 60: };
! 61: }
! 62: } else {
! 63: print NEW $_ || do {
! 64: warn "Can't write to $temp: $!\n";
! 65: unlink($temp);
! 66: };
! 67: }
! 68: }
! 69: }
! 70: close(OLD);
! 71: close(NEW);
! 72:
! 73: # Set owner/group/mode on tempfile and move to real location.
! 74: ($mode, $nlink, $uid, $gid) = (stat($keyfile))[2..5];
! 75: if (!defined($mode)) {
! 76: unlink($temp);
! 77: die "$0: Unable to stat $keyfile: $!\n";
! 78: }
! 79: if (!chmod($mode, $temp)) {
! 80: unlink($temp);
! 81: die "$0: Unable to set mode of $temp to $mode: $!\n";
! 82: }
! 83: if (!chown($uid, $gid, $temp)) {
! 84: unlink($temp);
! 85: die "$0: Unable to set owner of $temp to ($uid, $gid): $!\n";
! 86: }
! 87: # Leave temp file in place if rename fails. Might help in debugging.
! 88: rename($temp, $keyfile) || die "$0: Unable to rename $temp to $keyfile: $!\n";
! 89:
! 90: exit(0);