Unix-SavedIDs
view release on metacpan or search on metacpan
lib/Unix/SetUser.pm view on Meta::CPAN
# $Id$
package Unix::SetUser;
use warnings;
use strict;
use Carp;
use Unix::SavedIDs 0.004002;
use Data::Dumper;
#warn "\@INC = ".join(" ",@INC)."\n";
#warn "\%INC = ".Dumper(\%INC)."\n";
our $verbose = 0;
my $warncount = 0;
BEGIN {
use Exporter ();
our ($VERSION,@ISA,@EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(set_user);
$VERSION = 0.004003;
}
sub set_user {
## Figure Out IDs to Set
my($user,$group,@sup_groups) = @_;
my($uid,$gid,%sup_gids);
my $is_int = qr/^(\d+)$/o;
if ( !defined($user) ) {
croak "set_user() called with no arguments";
}
# get uids
if ( $user =~ $is_int ) {
$uid = $1;
}
else {
# get numeric uid if given non-numeric user name
$uid = getpwnam($user);
if ( !defined($uid) ) {
croak "User '$user' does not exist";
}
if ( $uid !~ $is_int ) {
croak "User id for '$user' is not an int. "
."This shouldn't ever happen";
}
$uid = $1;
}
# get primary gid
if ( defined($group) && $group =~ $is_int ) {
$gid = $1;
if ( !getgrgid($gid) ) {
croak "Primary group id '$gid' does not exist\n";
}
}
else {
# use user's primary group if no primary group specified
if ( !defined($group) ) {
$gid = (getpwuid($uid))[3];
if ( !defined($gid)) {
croak "Failed to get primary group ID for uid '$uid'";
}
}
else {
# get gid from group name
$gid = getgrnam($group);
if ( !defined($gid) ) {
croak "Primary group '$group' does not exist";
}
}
if ( $gid !~ $is_int ) {
croak "Primary group ID for '$user' is not an int. "
."This shouldn't ever happen";
}
}
# get supplemental groups
my @dont_exist;
foreach my $sup_group (@sup_groups) {
my $sup_gid;
if ( !defined($sup_group) ) {
croak "Supplemental group list contains 'undef'";
}
# if ints, make sure they exist
if ( $sup_group =~ $is_int ) {
$sup_gid = $1;
if ( $sup_gid == $gid || defined($sup_gids{$sup_gid})) {
# remove duplicates
next;
}
if ( !getgrgid($sup_gid) ) {
push(@dont_exist,$sup_group);
next;
}
}
# if not ints, convert text usernames to ints which tests existance
else {
$sup_gid = getgrnam($sup_group);
if ( !defined($sup_gid) ) {
push(@dont_exist,$sup_group);
next;
}
if ( $sup_gid !~ $is_int ) {
croak "Supplemental group id for group '$sup_group' is "
."not an int. This shouldn't ever happen";
}
if ( $sup_gid == $gid || defined($sup_gids{$sup_gid}) ) {
# duplicate
next;
}
}
$sup_gids{$sup_gid} = 1;
}
if ( @dont_exist ) {
croak "Specified supplemental group(s) '".join("', '",@dont_exist)
."' do(es) not exist(s)";
}
## Set Ids
( run in 2.219 seconds using v1.01-cache-2.11-cpan-cdf2f3d4e48 )