Config-Crontab-1.45/000755 000765 000024 00000000000 13076160355 014543 5ustar00scottstaff000000 000000 Config-Crontab-1.45/Changes000644 000765 000024 00000022346 13076160325 016042 0ustar00scottstaff000000 000000 Revision history for Perl extension Config::Crontab. Release 1.45 ---------------------------- commit eef68c773f42d73b5670a7c894b2f67914c83c95 Author: Scott Wiersdorf Date: Thu Apr 20 10:24:09 2017 -0600 use relative path in require (RT#120863) Release 1.44 ---------------------------- commit a81b708e1b5b023b6fc70ec7b68ce4cfcd1d5628 Author: Scott Wiersdorf Date: Mon Mar 20 14:24:08 2017 -0600 skip crontab writes unless explicitly asked for Release 1.43 ---------------------------- commit 2fedca514e2826bae41960295af20dc718db3256 Author: Scott Wiersdorf Date: Mon Feb 27 10:42:51 2017 -0700 fix lexical scope error introduced in PR#2; tests Release 1.42 ---------------------------- commit 337927a0840a7d3572b31c9c31c2911463e6bbc4 Author: Felipe Gasper Date: Fri Jan 6 15:39:46 2017 -0500 Use lexical filehandles rather than barewords (https://github.com/FGasper) Release 1.41 ---------------------------- commit 5ab21cf7b653915d792e76935606bf24462a11fb Author: Scott Wiersdorf Date: Thu May 26 19:00:26 2016 -0600 RT #114744 Release 1.40 ---------------------------- revision 1.8 date: 2014/01/09 04:50:04; author: scott; state: Exp; lines: +5 -4 - fix for multiple datetime wildcards Release 1.33 ---------------------------- revision 1.7 date: 2011/04/11 22:55:03; author: scott; state: Exp; lines: +8 -3 - check for SunOS crontab (RT#32658) Release 1.32 ---------------------------- revision 1.6 date: 2011/04/11 22:39:19; author: scott; state: Exp; lines: +2 -2 - add t/setup.pl to MANIFEST Release 1.31 ---------------------------- revision 1.5 date: 2011/04/11 22:29:11; author: scott; state: Exp; lines: +10 -7 - minor formatting changes - tests updated to Test::More - checks for crontab(1) in tests (RT#59578) - fewer stupid tests Release 1.30 ---------------------------- revision 1.4 date: 2008/10/27 16:31:46; author: scott; state: Exp; lines: +58 -19 - version 1.30 - modernize (no more 'use vars') - support for SuSE-specific 'no syslog' extension Release 1.21 ---------------------------- revision 1.3 date: 2007/07/18 19:55:59; author: scott; state: Exp; lines: +40 -3 - note about debian linux's 'crontab' command Release 1.20 ---------------------------- revision 1.2 (new CVS repository) date: 2006/04/18 22:08:38; author: scott; state: Exp; lines: +53 -3 - fix write('') to unset file() - add remove_tab() method to remove the crontab Release 1.10 ---------------------------- revision 1.37 date: 2005/06/10 22:14:50; author: scottw; state: Exp; lines: +132 -14 - support for reading other users' crontabs (as root) Release 1.06 ---------------------------- revision 1.36 date: 2005/05/04 21:24:03; author: scottw; state: Exp; lines: +162 -13 - pretty printing in system mode tests - select_blocks tests ---------------------------- revision 1.35 date: 2005/04/29 18:28:11; author: scottw; state: Exp; lines: +13 -3 - pass through the -system parameter ---------------------------- revision 1.34 date: 2005/04/28 04:16:53; author: scottw; state: Exp; lines: +63 -28 - support for system crontab Release 1.05 ---------------------------- revision 1.33 date: 2005/04/27 17:49:31; author: scottw; state: Exp; lines: +54 -6 - additional documentation for Event syntax ---------------------------- revision 1.32 date: 2005/04/27 16:42:24; author: scottw; state: Exp; lines: +52 -17 - add system-style parsing information and 'user' method Release 1.04 ---------------------------- revision 1.31 date: 2004/09/27 17:52:01; author: scottw; state: Exp; lines: +4 -3 - return if no object selecte Release 1.03 ---------------------------- revision 1.30 date: 2003/09/11 15:22:04; author: scottw; state: Exp; lines: +5 -5 - fix delete => remove typos Release 1.02 ---------------------------- revision 1.29 date: 2003/07/11 20:53:07; author: scottw; state: Exp; lines: +159 -69 - additional documentation, minor fixes - tests with pipe files Release 1.01 - First public release ---------------------------- revision 1.28 date: 2003/05/22 13:59:42; author: scottw; state: Exp; lines: +29 -15 - sysv notes - version increment - constructor notes ---------------------------- revision 1.27 date: 2003/05/21 22:22:31; author: scottw; state: Exp; lines: +4 -5 - fix bug with setting '*/2'-style datetime elements via 'datetime' method ---------------------------- revision 1.26 date: 2003/05/20 22:10:19; author: scottw; state: Exp; lines: +46 -1 - add 'replace' method to container class - add tests for 'replace' - work on cgi demo script ---------------------------- revision 1.25 date: 2003/05/20 00:11:01; author: scottw; state: Exp; lines: +1 -2 - whitespace change to module - add new example cgi program ---------------------------- revision 1.24 date: 2003/05/18 04:19:22; author: scottw; state: Exp; lines: +277 -120 - safe 'write' method for replacing existing (or making new) crontabs - activate/deactivate entire blocks with 'active' method - documentation ---------------------------- revision 1.23 date: 2003/05/16 23:37:01; author: scottw; state: Exp; lines: +3 -3 - fix missing C<> blocks around command-line examples ---------------------------- revision 1.22 date: 2003/05/16 23:34:59; author: scottw; state: Exp; lines: +1024 -677 - change 'parse' to 'read' in Config::Crontab - disallow non-block objects in Config::Crontab internals - much documentation - new crashme tests - working on a small tutorial ---------------------------- revision 1.21 date: 2003/05/16 04:48:53; author: scottw; state: Exp; lines: +13 -1 - auto-parse if '-file' is passed to constructor ---------------------------- revision 1.20 date: 2003/05/15 21:02:48; author: scottw; state: Exp; lines: +249 -132 - refactor Block->select and Crontab->select - fix parsing - documentation & test improvements ---------------------------- revision 1.19 date: 2003/05/15 14:47:09; author: scottw; state: Exp; lines: +25 -8 - tests for write method ---------------------------- revision 1.18 date: 2003/05/15 13:09:22; author: scottw; state: Exp; lines: +2 -2 - doc change ---------------------------- revision 1.17 date: 2003/05/15 05:14:51; author: scottw; state: Exp; lines: +4 -4 - fix some things 5.00503 didn't like (symbolic refs w/o parens, == with undef) Release 1.00 ---------------------------- revision 1.16 date: 2003/05/14 22:35:25; author: scottw; state: Exp; lines: +103 -49 - first complete version - working on SYOPSIS documentation section and a corresponding test suite ---------------------------- revision 1.15 date: 2003/05/12 23:41:13; author: scottw; state: Exp; lines: +279 -155 - created Container superclass for Crontab and Block classes - working on 'select' method and 'block' method - need to test up, down, first, last, etc (Container methods) ---------------------------- revision 1.14 date: 2003/05/11 03:56:16; author: scottw; state: Exp; lines: +78 -57 - implemented up, down, first, last for Block class - removed 'more' method, renamed 'less' to 'remove' - need to fixup documentation for some of these changes (marked FIXME) ---------------------------- revision 1.13 date: 2003/05/10 05:44:00; author: scottw; state: Exp; lines: +55 -15 - fix some 5.00503 bugs under strict - tidy up some initialization (use methods instead of data members) - "move" methods documented ---------------------------- revision 1.12 date: 2003/05/09 23:13:23; author: scottw; state: Exp; lines: +513 -143 - Block class fully documented; working on "move" methods/tests for block class ---------------------------- revision 1.11 date: 2003/05/08 23:44:07; author: scottw; state: Exp; lines: +363 -22 - documentation for Event, Env, and Comment classes complete - adding code for block manipulation ---------------------------- revision 1.10 date: 2003/05/08 04:25:03; author: scottw; state: Exp; lines: +143 -8 - Event object documented ---------------------------- revision 1.9 date: 2003/05/07 22:32:10; author: scottw; state: Exp; lines: +288 -3 - documentation fuller ---------------------------- revision 1.8 date: 2003/05/07 15:39:46; author: scottw; state: Exp; lines: +1 -1 - fix 'odd number of hash args' error for 5.00503 ---------------------------- revision 1.7 date: 2003/05/07 15:33:25; author: scottw; state: Exp; lines: +103 -53 - consistent event handling ---------------------------- revision 1.6 date: 2003/05/05 21:51:29; author: scottw; state: Exp; lines: +235 -294 - mostly functional ---------------------------- revision 1.5 date: 2003/05/02 22:09:28; author: scottw; state: Exp; lines: +40 -0 - changing how crontab files are parsed (data handed off to constructors which will either fail or succeed). ---------------------------- revision 1.4 date: 2003/04/24 04:16:27; author: scottw; state: Exp; lines: +11 -7 - moderate progress ---------------------------- revision 1.3 date: 2003/04/23 22:23:25; author: scottw; state: Exp; lines: +214 -53 - more progress; working comment, environment, and most of event subclasses ---------------------------- revision 1.2 date: 2003/04/23 04:48:23; author: scottw; state: Exp; lines: +140 -18 - work done in 'parse' method ---------------------------- revision 1.1 date: 2003/04/22 19:29:32; author: scottw; state: Exp; - initial checkin of crontab parser/writer Config-Crontab-1.45/Crontab.pm000644 000765 000024 00000265115 13076160133 016475 0ustar00scottstaff000000 000000 ############################################################ ############################################################ ## ## Scott Wiersdorf ## Created: Fri May 9 14:03:01 MDT 2003 ## Updated: $Id$ ## ## Config::Crontab - a crontab(5) parser ## ## This file contains the following classes: ## ## - Config::Crontab - the top level crontab object ## - Config::Crontab::Block - crontab block (paragraph) handling ## - Config::Crontab::Event - "5 0 * * * /bin/command" ## - Config::Crontab::Env - "VAR=value" ## - Config::Crontab::Comment - "## a comment" ## - Config::Crontab::Base - base class from which all other ## Config::Crontab classes inherit ## - Config::Crontab::Container - base class from which Crontab and ## Block classes inherit ## ############################################################ ############################################################ ## to do: if -file = /etc/crontab, set system => 1 ## to do: if adding a non-block to a $ct file, make a block for us automatically ## a crontab object is a list of Block objects (see below) This class ## (Config::Crontab) is for working with crontab files as a whole. package Config::Crontab; use strict; use warnings; use Carp; use 5.006_001; our @ISA = qw(Config::Crontab::Base Config::Crontab::Container); ## these two are for the 'write' method use Fcntl; use File::Temp qw(:POSIX); our $VERSION = '1.45'; sub init { my $self = shift; my %args = @_; $self->file(''); $self->mode('block'); $self->squeeze(1); ## only in block mode $self->strict(0); $self->blocks([]); $self->error(''); $self->system(0); $self->owner(''); $self->owner_re( '[^a-zA-Z0-9\._-]' ); $self->file( $args{'-file'}) if exists $args{'-file'}; $self->mode( $args{'-mode'}) if exists $args{'-mode'}; $self->squeeze( $args{'-squeeze'}) if exists $args{'-squeeze'}; $self->strict( $args{'-strict'}) if exists $args{'-strict'}; $self->system( $args{'-system'}) if exists $args{'-system'}; $self->owner( $args{'-owner'}) if exists $args{'-owner'}; $self->owner_re( $args{'-owner_re'}) if exists $args{'-owner_re'}; ## auto-parse if file is specified $self->read if $self->file; return 1; } sub read { my $self = shift; my %args = @_; $self->file( $args{'-file'}) if exists $args{'-file'}; $self->mode( $args{'-mode'}) if exists $args{'-mode'}; $self->squeeze( $args{'-squeeze'}) if exists $args{'-squeeze'}; $self->strict( $args{'-strict'}) if exists $args{'-strict'}; $self->system( $args{'-system'}) if exists $args{'-system'}; $self->owner( $args{'-owner'}) if exists $args{'-owner'}; $self->owner_re( $args{'-owner_re'}) if exists $args{'-owner_re'}; ## set default system crontab if( $self->system && ! $self->file ) { $self->file('/etc/crontab'); } my $fh; ## parse the file accordingly if( $self->file ) { open $fh, $self->file or do { $self->error($!); if( $self->strict ) { croak "Could not open " . $self->file . ": " . $self->error . "\n"; } return; } } else { my $crontab_cmd = "crontab -l 2>/dev/null|"; if( $self->owner ) { if( $^O eq 'SunOS' ) { $crontab_cmd = "crontab -l " . $self->owner . " 2>/dev/null|"; } else { $crontab_cmd = "crontab -u " . $self->owner . " -l 2>/dev/null|"; } } open $fh, $crontab_cmd or do { $self->error($!); if( $self->strict ) { croak "Could not open pipe from crontab: " . $self->error . "\n"; } return; } } ## reset internal block list and errors $self->blocks([]); $self->error(''); PARSE: { local $/; ## each line is a block if( $self->mode eq 'line' ) { $/ = "\n"; } ## whole file is a block elsif( $self->mode eq 'file' ) { $/ = undef; } ## each paragraph (\n\n+) is a block else { $/ = ( $self->squeeze ? '' : "\n\n" ); } local $_; while( <$fh> ) { chomp; $self->last( new Config::Crontab::Block( -system => $self->system, -data => $_ ) ); } } close $fh; } ## this is needed for Config::Crontab::Container class methods *elements = \&blocks; sub blocks { my $self = shift; my $blocks = shift; if( ref($blocks) eq 'ARRAY' ) { $self->{'_blocks'} = $blocks; } ## return only blocks (in case of accidental non-block pushing) return grep { UNIVERSAL::isa($_, 'Config::Crontab::Block') } grep { ref($_) } @{$self->{'_blocks'}}; } sub select { my $self = shift; my @results = (); push @results, $_->select(@_) for $self->blocks; @results; } sub select_blocks { my $self = shift; my %crit = @_; my @results = (); unless( keys %crit ) { @results = $self->blocks; } while( my($key, $value) = each %crit ) { $key =~ s/^\-//; ## strip leading hyphen if( $key eq 'index' ) { unless( defined $value ) { if( $self->strict ) { carp "index value undefined\n"; } next; } ## a list ref of integers if( ref($value) eq 'ARRAY' ) { push @results, @{$self->{'_blocks'}}[@$value]; } ## an integer elsif( $value =~ /^\d+$/ ) { push @results, @{$self->{'_blocks'}}[$value]; } else { if( $self->strict ) { carp "index value not recognized\n"; } } } else { if( $self->strict ) { carp "Unknown block selection type '$key'\n"; } } } @results; } sub block { my $self = shift; my $obj = shift or return; my $rblock; BLOCK: for my $block ( $self->blocks ) { for my $line ( $block->lines ) { if( $line == $obj ) { $rblock = $block; last BLOCK; } } } return $rblock; } sub remove { my $self = shift; my @objs = @_; if( @objs ) { for my $obj ( @objs ) { next unless defined $obj && ref($obj); unless( UNIVERSAL::isa($obj, 'Config::Crontab::Block') ) { if( $self->block($obj) ) { $self->block($obj)->remove($obj); } ## a non-block object in our crontab file! else { undef $obj; } next; } for my $block ( @{$self->{'_blocks'}} ) { next unless defined $block && ref($block); if( $block == $obj ) { undef $block; } } } ## strip out undefined objects $self->blocks([ grep { defined } $self->elements ]); } return $self->elements; } ## same as 'crontab -u user file' sub write { my $self = shift; my $file = shift; ## see if a file is present, allow for '' if( defined $file ) { $self->file($file); } if( $self->file ) { open my $ct, ">" . $self->file or croak "Could not open " . $self->file . ": $!\n"; print {$ct} $self->dump; close $ct; } ## use a temporary filename else { my $tmpfile; my $ct; do { $tmpfile = tmpnam() } until sysopen($ct, $tmpfile, O_RDWR|O_CREAT|O_EXCL); print {$ct} $self->dump; close $ct; my $crontab; if( my $owner = $self->owner ) { $crontab = `crontab -u $owner $tmpfile 2>&1`; } else { $crontab = `crontab $tmpfile 2>&1`; } chomp $crontab; unlink $tmpfile; if( $crontab || $? ) { $self->error($crontab); if( $self->strict ) { carp "Error writing crontab (crontab exited with status " . ($? >> 8) . "): " . $self->error; } return; } } return 1; } sub remove_tab { my $self = shift; my $file = shift; ## see if a file is present, allow for '' if( defined $file ) { $self->file($file); } if( $self->file ) { unlink $self->file; } else { my $output = ''; if( my $owner = $self->owner ) { $output = `crontab -u $owner -r 2>&1`; } else { $output = `yes | crontab -r 2>&1`; } chomp $output; ## FIXME: what if no $output, but only '$?' ? if( $output || $? ) { $self->error($output); if( $self->strict ) { carp "Error removing crontab (crontab exited with status " . ($? >> 8) ."): " . $self->error; } return; } } return 1; } sub dump { my $self = shift; my $ret = ''; for my $block ( $self->blocks ) { $ret .= "\n" if $ret && $block->dump; ## empty blocks should not invoke a newline $ret .= $block->dump; } return $ret; } sub owner { my $self = shift; if( @_ ) { my $owner = shift; if( $owner ) { unless( defined( getpwnam($owner) ) ) { $self->error("Unknown user: $owner"); if( $self->strict ) { croak $self->error; } return; } if( $owner =~ $self->owner_re ) { $self->error("Illegal username: $owner"); if( $self->strict ) { croak $self->error; } return; } } $self->{_owner} = $owner; } return ( defined $self->{_owner} ? $self->{_owner} : '' ); } sub owner_re { my $self = shift; if( @_ ) { my $re = shift; $self->{_owner_re} = qr($re); } return ( defined $self->{_owner_re} ? $self->{_owner_re} : qr() ); } ############################################################ ############################################################ =head1 NAME Config::Crontab - Read/Write Vixie compatible crontab(5) files =head1 SYNOPSIS use Config::Crontab; #################################### ## making a new crontab from scratch #################################### my $ct = new Config::Crontab; ## make a new Block object my $block = new Config::Crontab::Block( -data => <<_BLOCK_ ); ## mail something to joe at 5 after midnight on Fridays MAILTO=joe 5 0 * * Fri /bin/someprogram 2>&1 _BLOCK_ ## add this block to the crontab object $ct->last($block); ## make another block using Block methods $block = new Config::Crontab::Block; $block->last( new Config::Crontab::Comment( -data => '## do backups' ) ); $block->last( new Config::Crontab::Env( -name => 'MAILTO', -value => 'bob' ) ); $block->last( new Config::Crontab::Event( -minute => 40, -hour => 3, -command => '/sbin/backup --partition=all' ) ); ## add this block to crontab file $ct->last($block); ## write out crontab file $ct->write; ############################### ## changing an existing crontab ############################### my $ct = new Config::Crontab; $ct->read; ## comment out the command that runs our backup $_->active(0) for $ct->select(-command_re => '/sbin/backup'); ## save our crontab again $ct->write; ############################### ## read joe's crontab (must have root permissions) ############################### ## same as "crontab -u joe -l" my $ct = new Config::Crontab( -owner => 'joe' ); $ct->read; =head1 DESCRIPTION B provides an object-oriented interface to Vixie-style crontab(5) files for Perl. A B object allows you to manipulate an ordered set of B, B, or B objects (also included with this package). Descriptions of these packages may be found below. In short, B reads and writes crontab(5) files (and does a little pretty-printing too) using objects. The general idea is that you create a B object and associate it with a file (if unassociated, it will work over a pipe to C). From there, you can add lines to your crontab object, change existing line attributes, and write everything back to file. =over 4 =item NOTE: B does I (currently) do validity checks on your data (i.e., dates out of range, etc.). However, if the call to B fails when you invoke B, B will return I and set B with the error message returned from the B command. Future development may tend toward more validity checks. =back Now, to successfully navigate the module's ins and outs, we'll need a little terminology lesson. =head2 Terminology B (hereafter simply B) sees a C file in terms of I. A block is simply an ordered set of one or more lines. Blocks are separated by two or more newlines. For example, here is a crontab file with two blocks: ## a comment 30 4 * * * /bin/some_command ## another comment ENV=some_value 50 9 * * 1-5 /bin/reminder --meeting=friday The first block contains two B objects: a B object and an B object. The second block contains an B object in addition to a B object and an B object. The B class, then, consists of zero or more B objects. B objects have these three basic elements: =over 4 =item B Any lines in a crontab that look like these are B objects: 5 10 * * * /some/command @reboot /bin/mystartup.sh ## 0 0 * * Fri /disabled/command Notice that commented out event lines are still considered B objects. B objects are described below in the B package description. Please refer to it for details on manipulating B objects. =item B Any lines in a crontab that look like these are B objects: MAILTO=joe SOMEVAR = some_value #DISABLED=env_setting Notice that commented out environment lines are still considered B objects. B objects are described below in the B package description. Please refer to it for details on manipulating B objects. =item B Any lines containing only whitespace or lines beginning with a pound sign (but are not B or B objects) are B objects: ## this is a comment (imagine somewhitespace here) B objects are described below in the B package description. Please refer to it for details on manipulating B objects. =back =head2 Illustration Here is a simple crontab file: MAILTO=joe@schmoe.org ## send reminder in April 3 10 * Apr Fri joe echo "Friday a.m. in April" The file consists of an environment variable setting (MAILTO), a comment, and a command to run. After parsing the above file, B would break it up into the following objects: +---------------------------------------------------------+ | Config::Crontab object | | | | +---------------------------------------------------+ | | | Config::Crontab::Block object | | | | | | | | +---------------------------------------------+ | | | | | Config::Crontab::Env object | | | | | | | | | | | | -name => MAILTO | | | | | | -value => joe@schmoe.org | | | | | | -data => MAILTO=joe@schmoe.org | | | | | +---------------------------------------------+ | | | +---------------------------------------------------+ | | | | +---------------------------------------------------+ | | | Config::Crontab::Block object | | | | | | | | +---------------------------------------------+ | | | | | Config::Crontab::Comment object | | | | | | | | | | | | -data => ## send reminder in April | | | | | +---------------------------------------------+ | | | | | | | | +---------------------------------------------+ | | | | | Config::Crontab::Event Object | | | | | | | | | | | | -datetime => 3 10 * Apr Fri | | | | | | -special => (empty) | | | | | | -minute => 3 | | | | | | -hour => 10 | | | | | | -dom => * | | | | | | -month => Apr | | | | | | -dow => Fri | | | | | | -user => joe | | | | | | -command => echo "Friday a.m. in April" | | | | | +---------------------------------------------+ | | | +---------------------------------------------------+ | +---------------------------------------------------------+ You'll notice the main Config::Crontab object encapsulates the entire file. The parser found two B objects: the lone MAILTO variable setting, and the comment and command (together). Two or more newlines together in a crontab file constitute a block separator. This allows you to logically group commands (as most people do anyway) in the crontab file, and work with them as a Config::Crontab::Block objects. The second block consists of a B object and an B object, shown are some of the data methods you can use to get or set data in those objects. =head2 Practical Usage: A Brief Tutorial Now that we know what B objects look like and what they're called, let's play around a little. Let's say we have an existing crontab on many machines that we want to manage. The crontab contains some machine-dependent information (e.g., timezone, etc.), so we can't just copy a file out everywhere and replace the existing crontab. We need to edit each crontab individually, specifically, we need to change the time when a particular job runs: 30 2 * * * /usr/local/sbin/pirate --arg=matey to 3:30 am because of daylight saving time (i.e., we don't want this job to run twice). We can do something like this: use Config::Crontab; my $ct = new Config::Crontab; $ct->read; my ($event) = $ct->select(-command_re => 'pirate --arg=matey'); $event->hour(3); $ct->write; All done! This shows us a couple of subtle but important points: =over 4 =item * The B object must have its B method invoked for it to read the crontab file. =item * The B into scalar context and we would get the number of items in the list instead of the list itself). =item * The I methods for B (and other) objects are usually invoked the same way as their I method except with an argument. =item * We must write the crontab back out to file with the B method. =back Here's how we might do the same thing in a one-line Perl program: perl -MConfig::Crontab -e '$ct=new Config::Crontab; $ct->read; \ ($ct->select(-command_re=>"pirate --arg=matey"))[0]->hour(3); \ $ct->write' Nice! Ok. Now we need to add a new crontab entry: 35 6 * * * /bin/alarmclock --ring We can do it like this: $event = new Config::Crontab::Event( -minute => 36, -hour => 6, -command => '/bin/alarmclock --ring'); $block = new Config::Crontab::Block; $block->last($event); $ct->last($block); or like this: $event = new Config::Crontab::Event( -data => '35 6 * * * /bin/alarmclock --ring' ); $ct->last(new Config::Crontab::Block( -lines => [$event] )); or like this: $ct->last(new Config::Crontab::Block(-data => "35 6 * * * /bin/alarmclock --ring")); We learn the following things from this example: =over 4 =item * Only B objects can be added to B objects (see L). B objects may be added via the B method (and several other methods, including B, B, B, B, and B). =item * B objects can be populated in a variety of ways, including the B<-data> attribute (a string which may--and frequently does--span multiple lines via a 'here' document), the B<-lines> attribute (which takes a list reference), and the B method. In addition to the B method, B objects use the same methods for adding and moving objects that the B object does: B, B, B, B, B, and B. =back After the B section, the remainder of this document is a reference manual and describes the methods available (and how to use them) in each of the 5 classes: B, B, B, B, and B. The reader is also encouraged to look at the example CGI script in the F directory and the (somewhat contrived) examples in the F (testing) directory with this distribution. =head2 Module Utility B is a useful module by virtue of the "one-liner" test. A useful module must do useful work (editing crontabs is useful work) economically (i.e., useful work must be able to be done on a single command-line that doesn't wrap more than twice and can be understood by an adept Perl programmer). Graham Barr's B module (actually, most of Graham's work falls in this category) is a good example of a useful module. So, with no more ado, here are some useful one-liners with B: =over 4 =item * uncomment all crontab events whose command contains the string 'fetchmail' perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \ $_->active(1) for $c->select(-command_re => "fetchmail"); $c->write' =item * remove the first crontab block that has '/bin/unwanted' as a command perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \ $c->remove($c->block($c->select(-command_re => "/bin/unwanted"))); \ $c->write' =item * reschedule the backups to run just Monday thru Friday: perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \ $_->dow("1-5") for $c->select(-command_re => "/sbin/backup"); $c->write' =item * reschedule the backups to run weekends too: perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \ $_->dow("*") for $c->select(-command_re => "/sbin/backup"); $c->write' =item * change all 'MAILTO' environment settings in this crontab to 'joe@schmoe.org': perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \ $_->value(q!joe@schmoe.org!) for $c->select(-name => "MAILTO"); $c->write' =item * strip all comments from a crontab: perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \ $c->remove($c->select(-type => "comment")); $c->write' =item * disable an entire block of commands (the block that has the word 'Friday' in it): perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \ $c->block($c->select(-data_re => "Friday"))->active(0); $c->write' =item * copy one user's crontab to another user: perl -MConfig::Crontab -e '$c = new Config::Crontab(-owner => "joe"); \ $c->read; $c->owner("mike"); $c->write' =back =head1 PACKAGE Config::Crontab This section describes B objects (hereafter simply B objects). A B object is an abstracted way of dealing with an entire B file. The B class has methods to allow you to select, add, or remove B objects as well as read and parse crontab files and write crontab files. =head2 init([%args]) This method is called implicitly when you instantiate an object via B. B takes the same arguments as B and B. If the B<-file> argument is specified (and is non-false), B will invoke B automatically with the B<-file> value. Use B to re-initialize an object. Example: ## auto-parses foo.txt in implicit call to init $ct = new Config::Crontab( -file => 'foo.txt' ); ## re-initialize the object with default values and a new file $ct->init( -file => 'bar.txt' ); =head2 strict([boolean]) B enforces the following constraints: =over 4 =item * if the file specified by the B method (or B<-file> attribute in B) does not exist at the time B is invoked, B sets B and dies: "Could not open (filename): (reason)". If strict is disabled, B returns I (B is set). =item * If the file specified by the B method (or B<-file> attribute in B) cannot be written to, or the C command fails, B sets B and warns: "Could not open (filename): (reason)". If strict is disabled, B returns I (B is set). =item * Croaks if an illegal username is specified in the B<-owner> parameter. =back Examples: ## disable strict (default) $ct->strict(0); =head2 system([boolean]) B tells B to assume that the crontab object is after the pattern described in L with an extra I field before the I field: @reboot joeuser /usr/local/bin/fetchmail -d 300 where the given command will be executed by said user. when a crontab file (e.g., F) is parsed without B enabled, the I field will be lumped in with the command. When enabled, the user field will be accessible in each event object via the B method (see L in the B documentation below). =head2 owner([string]) B sets the owner of the crontab. If you're running Config::Crontab as a privileged user (e.g., "root"), you can read and write user crontabs by specifying B either in the constructor, during B, or using B before a B or B method is called: $c = new Config::Crontab( -owner => 'joe' ); $c->read; ## reading joe's crontab Or another way: $c = new Config::Crontab; $c->owner('joe'); $c->read; ## reading joe's crontab You can use this to copy a crontab from one user to another: $c->owner('joe'); $c->read; $c->owner('bob'); $c->write; =head2 owner_re([regex]) B is strict in what it will allow for a username, since this information internally is passed to a shell. If the username specified is not a user on the system, B will set B with "Illegal username" and return I; if B mode is enabled, B will croak with the same error. Further, once the username is determined valid, the username is then checked against a regular expression to thwart null string attacks and other maliciousness. The default regular expression used to check for a safe username is: /[^a-zA-Z0-9\._-]/ If the pattern matches (i.e., if any characters other than the ones above are found in the supplied username), B will set B with "Illegal username" and return I. If B mode is enabled, B will croak with the same error. $c->owner_re('[^a-zA-Z0-9_\.-#]'); ## allow # in usernames =head2 read([%args]) Parses the crontab file specified by B. If B is not set (or is false in some way), the crontab will be read from a pipe to C. B optionally takes the same arguments as B and B in C value> style lists. Until you B the crontab, the B object will be uninitialized and will contain no data. You may re-read existing objects to get new crontab data, but the object will retain whatever other attributes (e.g., strict, etc.) it may have from when it was initialized (or later attributes were changed) but will reset B. Use B to completely refresh an object. If B fails, B will be set. Examples: ## reads the crontab for this UID (via crontab -l) $ct = new Config::Crontab; $ct->read; ## reads the crontab from a file $ct = new Config::Crontab; $ct->read( -file => '/var/cronbackups/cron1' ); ## same thing as above $ct = new Config::Crontab( -file => '/var/cronbackups/cron1' ); $ct->read; ## '-file' attribute already set ## ditto using 'file' method $ct = new Config::Crontab; $ct->file('/var/cronbackups/cron1'); $ct->read; ## ditto, using a pipe $ct = new Config::Crontab; $ct->file('cat /var/cronbackups/cron1|'); $ct->read; ## ditto, using 'read' method $ct = new Config::Crontab; $ct->read( -file => 'cat /var/cronbackups/cron1|'); ## now fortified with error-checking $ct->read or do { warn $ct->error; return; }; =cut ## FIXME: need to say something about squeeze here, but squeeze(0) ## doesn't seem to work correctly (i.e., it still squeezes the file) =head2 mode([mode]) Returns the current parsing mode for this object instance. If a mode is passed as an argument, next time this instance parses a crontab file, it will use this new mode. Valid modes are I, I (the default), or I. Example: ## re-read this crontab in 'file' mode $ct->mode('file'); $ct->read; =head2 blocks([\@blocks]) Returns a list of B objects in this crontab. The B method also takes an optional list reference as an argument to set this crontab's block list. Example: ## get blocks, remove comments and dump for my $block ( $ct->blocks ) { $block->remove($block->select( -type => 'comment' ) ); $block->remove($block->select( -type => 'event', -active => 0 ); print $block->dump; } ## one way to remove unwanted blocks from a crontab my @keepers = $ct->select( -type => 'comment', -data_re => 'keep this block' ); $ct->blocks(\@keepers); ## another way to do it (notice 'nre' instead of 're') $ct->remove($ct->select( -type => 'comment', -data_nre => 'keep this block' )); =head2 select([%criteria]) Returns a list of crontab lines that match the specified criteria. Multiple criteria may be specified. If no criteria are specified, B method first: ## the first block in the crontab file is an environment variable ## declaration: NAME=value @blocks = $ct->select_blocks( -index => 1 ); print "This environment variable value is " . ($block[0]->lines)[0]->value . "\n"; =head2 block($line) Returns the block that this line belongs to. If the line is not found in any blocks, I is returned. I<$line> must be a B, B, or B object. Examples: ## will always return undef for new objects; you'd never really do this $block = $ct->block( new Config::Crontab::Comment(-data => '## foo') ); ## returns a Block object $block = $ct->block($existing_crontab_line); $block->dump; ## find and remove the block in which '/bin/baz' is executed my $event = $ct->select( -type => 'event', -command_re => '/bin/baz'); $block = $ct->block($event); $ct->remove($block); =head2 remove($block) Removes a block from the crontab file (if a block is specified) or a crontab line from its block (if a crontab line object is specified). Example: ## remove this block from the crontab $ct->remove($block); ## remove just a line from its block $ct->remove($line); =head2 replace($oldblock, $newblock) Replaces I<$oldblock> with I<$newblock>. Returns I<$oldblock> if successful, I otherwise. Example: ## look for the block containing 'oldtuesday' and replace it with our new block $newblock = new Config::Crontab::Block( -data => '5 10 * * Tue /bin/tuesday' ); my $oldblock = $ct->block($ct->select(-data_re => 'oldtuesday')); $ct->replace($oldblock, $newblock); =head2 up($block), down($block) These methods move a single B object up or down in the B object's internal array. If the B object is not already a member of this array, it will be added to the array in the first position (for B) and in the last position (for B. See also B and B and B and B in the B class. Example: $ct->up($block); ## move this block up one position =head2 first(@block), last(@block) These methods move the B object(s) to the first or last positions in the B object's internal array. If the block is not already a member of the array, it will be added in the first or last position respectively. Example: $ct->last(new Config::Crontab::Block( -data => <<_BLOCK_ )); ## eat ice cream 5 * * * 1-5 /bin/eat --cream=ice _BLOCK_ =head2 before($look_for, @blocks), after($look_for, @blocks) These methods move the B object(s) to the position immediately before or after the I<$look_for> (or reference) block in the B object's internal array. If the objects are not members of the array, they will be added before or after the reference block respectively. If the reference object does not exist in the array, the blocks will be moved (or added) to the beginning or end of the array respectively (like B and B). Example: ## search for a block containing a particular event (line) $block = $ct->block($ct->select(-command_re => '/bin/foo')); ## add the new blocks immediately after this block $ct->after($block, @new_blocks); =head2 write([$filename]) Writes the crontab to the file specified by the B method. If B is not set (or is false), B will attempt to write to a temporary file and load it via the C program (e.g., C). You may specify an optional filename as an argument to set B, which will then be used as the filename. If B fails, B will be set. Example: ## write out crontab $ct->write or do { warn "Error: " . $ct->error . "\n"; return; }; ## set 'file' and write simultaneously (future calls to read and ## write will use this filename) $ct->write('/var/mycronbackups/cron1.txt'); ## same thing $ct->file('/var/mycronbackups/cron1.txt'); $ct->write; =head2 remove_tab([file]) Removes a crontab. If B is set, that file will be unlinked. If B is not set (or is false), B will attempt to remove the selected user's crontab via F or F for the current user id. If B fails, B will be set. Example: $ct->remove_tab(''); ## unset file() and remove the current user's crontab =head2 error([string]) Returns the last error encountered (usually during a file I/O operation). Pass an empty string to reset (calling B will also reset it). Example: print "The last error was: " . $ct->error . "\n"; $ct->error(''); =head2 dump Returns a string containing the crontab file. Example: ## show crontab print $ct->dump; ## same as 'crontab -l' except pretty-printed $ct = new Config::Crontab; $ct->read; print $ct->dump; =cut ############################################################ ############################################################ package Config::Crontab::Block; use strict; use warnings; use Carp; our @ISA = qw(Config::Crontab::Base Config::Crontab::Container); sub init { my $self = shift; my %args = @_; $self->lines([]); ## initialize $self->strict(0); $self->system(0); $self->lines($args{'-lines'}) if defined $args{'-lines'}; $self->strict($args{'-strict'}) if defined $args{'-strict'}; $self->system($args{'-system'}) if defined $args{'-system'}; my $rv = 1; if( defined $args{'-data'} ) { $self->lines([]); $rv = $self->data($args{'-data'}); } return ( defined $rv ? 1 : undef ); } sub data { my $self = shift; my $data = shift; my @lines = (); if( defined $data ) { if( ref($data) eq 'ARRAY' ) { @lines = @$data; } elsif( $data ) { @lines = split(/\n/, $data); } elsif( $data eq '' ) { @lines = ($data); } else { @lines = (); } for my $line ( @lines ) { my $obj; if( $obj = new Config::Crontab::Event(-data => $line, -system => $self->system) ) { } elsif( $obj = new Config::Crontab::Env(-data => $line) ) { } elsif( $obj = new Config::Crontab::Comment(-data => $line) ) { } else { if( $self->strict ) { carp "Skipping illegal line in block: $line\n"; } next; } $self->last($obj); } } my $ret = ''; for my $obj ( $self->lines ) { $ret .= "\n" if $ret; ## empty objects are empty lines, so we do a newline always $ret .= $obj->dump; } $ret .= "\n" if $ret; return $ret; } ## this is needed for Config::Crontab::Container class methods *elements = \&lines; sub lines { my $self = shift; my $objs = shift; if( ref($objs) eq 'ARRAY' ) { $self->{'_lines'} = $objs; } return @{$self->{'_lines'}}; } sub select { my $self = shift; my %crit = @_; ## return all lines unless criteria specified return $self->lines unless scalar keys %crit; my @results = (); LINE: for my $line ( $self->lines ) { my $j = scalar keys %crit; ## reset keys while( my($key,$value) = each %crit ) { $key =~ s/^\-//; ## strip leading hyphen ## FIXME: would be nice to have a negated 'type' option or a re ## special case for 'type' if( $key eq 'type' ) { if( $value eq 'event' ) { next LINE unless UNIVERSAL::isa($line, 'Config::Crontab::Event'); } elsif( $value eq 'env' ) { next LINE unless UNIVERSAL::isa($line, 'Config::Crontab::Env'); } elsif( $value eq 'comment' ) { next LINE unless UNIVERSAL::isa($line, 'Config::Crontab::Comment'); } else { if( $self->strict ) { carp "Unknown object type '$value'\n"; } next LINE; } } ## not special 'type' case else { no strict 'refs'; if( $key =~ /^(.+)_re$/ ) { next LINE unless $line->$1() =~ qr($value); } elsif( $key =~ /^(.+)_nre$/ ) { next LINE unless $line->$1() !~ qr($value); } else { next LINE unless $line->$key() eq $value; } } } push @results, $line; } return @results; } sub remove { my $self = shift; my @objs = @_; if( @objs ) { for my $obj ( @objs ) { next unless defined $obj && ref($obj); for my $line ( @{$self->{'_lines'}} ) { next unless defined $line && ref($line); if( $line == $obj ) { undef $line; } } } ## strip out undefined objects $self->elements([ grep { defined } $self->elements ]); } return $self->elements; } sub active { my $self = shift; return 1 unless @_; my $active = shift; local $_; $_->active($active) for $self->select(-type => 'env'); $_->active($active) for $self->select(-type => 'event'); return $active; } sub nolog { my $self = shift; return 1 unless @_; my $nolog = shift; local $_; $_->nolog($nolog) for $self->select(-type => 'event'); return $nolog; } ############################################################ ############################################################ =head1 PACKAGE Config::Crontab::Block This section describes B objects (hereafter referred to as B objects). A B object is an abstracted way of dealing with groups of crontab(5) lines. Depending on how B parsed the file (see the B and B methods in B above), a block may consist of: =over 4 =item a single line (e.g., a crontab event, environment setting, or comment) =item a "paragraph" of lines (a group of lines, each group separated by at least two newlines). This is the default parsing mode. =item the entire crontab file =back The default for B is to read in I (paragraph) mode. This allows you to group lines that have a similar purpose as well as order lines within a block (e.g., often you want an environment setting to take effect before certain cron commands execute). An illustration may be helpful: =over 4 =item B Line Block Block Line Entry 1 1 1 ## grind disks 2 1 2 5 5 * * * /bin/grind 3 1 3 4 2 1 ## backup reminder to joe 5 2 2 MAILTO=joe 6 2 3 5 0 * * Fri /bin/backup 7 2 4 8 3 1 ## meeting reminder to bob 9 3 2 MAILTO=bob 10 3 3 30 9 * * Wed /bin/meeting Notice that each block has its own internal line numbering. Vertical space has been inserted between blocks to clarify block structures. Block mode parsing is the default. =item B Line Block Block Line Entry 1 1 1 ## grind disks 2 2 1 5 5 * * * /bin/grind 3 3 1 4 4 1 ## backup reminder to joe 5 5 1 MAILTO=joe 6 6 1 5 0 * * Fri /bin/backup 7 7 1 8 8 1 ## meeting reminder to bob 9 9 1 MAILTO=bob 10 10 1 30 9 * * Wed /bin/meeting Notice that each line is also a block. You normally don't want to read in line mode unless you don't have paragraph breaks in your crontab file (the dumper prints a newline between each block; with each line being a block you get an extra newline between each line). =item B Line Block Block Line Entry 1 1 1 ## grind disks 2 1 2 5 5 * * * /bin/grind 3 1 3 4 1 4 ## backup reminder to joe 5 1 5 MAILTO=joe 6 1 6 5 0 * * Fri /bin/backup 7 1 7 8 1 8 ## meeting reminder to bob 9 1 9 MAILTO=bob 10 1 10 30 9 * * Wed /bin/meeting Notice that there is only one block in file mode, and each line is a block line (but not a separate block). =back =head1 METHODS This section describes methods accessible from B objects. =head2 new([%args]) Creates a new B object. You may create B objects in any of the following ways: =over 4 =item Empty $event = new Config::Crontab::Block; =item Fully Populated $event = new Config::Crontab::Block( -data => <<_BLOCK_ ); ## a comment 5 19 * * Mon /bin/fhe --turn=dad _BLOCK_ =back Constructor attributes available in the B method take the same arguments as their method counterparts (described below), except that the names of the attributes must have a hyphen ('-') prepended to the attribute name (e.g., 'lines' becomes '-lines'). The following is a list of attributes available to the B method: =over 4 =item B =item B =back If the B<-data> attribute is present in the constructor when other attributes are also present, the B<-data> attribute will override all other attributes. Each of these attributes corresponds directly to its similarly-named method. Examples: ## create an empty block object & populate it with the data method $block = new Config::Crontab::Block; $block->data( <<_BLOCK_ ); ## via a 'here' document ## 2:05a Friday backup MAILTO=sysadmin@mydomain.ext 5 2 * * Fri /sbin/backup /dev/da0s1f _BLOCK_ ## create a block in the constructor (also via 'here' document) $block = new Config::Crontab::Block( -data => <<_BLOCK_ ); ## 2:05a Friday backup MAILTO=sysadmin@mydomain.ext 5 2 * * Fri /sbin/backup /dev/da0s1f _BLOCK_ ## create an array of crontab objects my @lines = ( new Config::Crontab::Comment(-data => '## run bar'), new Config::Crontab::Event(-data => '5 8 * * * /foo/bar') ); ## create a block object via lines attribute $block = new Config::Crontab::Block( -lines => \@lines ); ## ...or with lines method $block->lines(\@lines); ## @lines is an array of crontab objects If bogus data is passed to the constructor, it will return I instead of an object reference. If there is a possiblility of poorly formatted data going into the constructor, you should check the object variable for definedness before using it. If the B<-data> attribute is present in the constructor when other attributes are also present, the B<-data> attribute will override all other attributes. =head2 data([string]) Get or set a raw block. Internally, B passes its arguments to other objects for parsing when a parameter is present. Example: ## re-initialize this block $block->data("## comment\n5 * * * * /bin/checkup"); print $block->data; Block data is terminated with a final newline. =head2 lines([\@objects]) Get block data as a list of B objects. Set block data using a list reference. Example: $block->lines( [ new Config::Crontab::Comment( -data => "## run backup" ), new Config::Crontab::Event( -data => "5 4 * * 1-5 /sbin/backup" ) ] ); ## sorta like $block->dump for my $obj ( $block->lines ) { print $obj->dump . "\n"; } ## a clumsy way to "unshift" a new event $block->lines( [new Config::Crontab::Comment(-data => '## hi mom!'), $block->lines] ); ## the right way to add a new event $block->first( new Config::Crontab::Comment(-data => '## hi mom!') ); print $_->dump for $block->lines; =head2 select([%criteria]) Returns a list of B, B, or B objects from a block that match the specified criteria. Multiple criteria may be specified. Field names should be preceded by a hyphen (though without a hyphen is acceptable too; we use hyphens to avoid the need for quoting keys and avoid potential bareword collisions). If not criteria are specified, B