| 1 | package Ubic::AccessGuard; | ||
| 2 | $Ubic::AccessGuard::VERSION = '1.59'; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | # ABSTRACT: guard for operations with temporarily different effective uid | ||
| 7 | |||
| 8 | |||
| 9 | use Params::Validate; | ||
| 10 | use Ubic::Result qw(result); | ||
| 11 | use Ubic::Credentials; | ||
| 12 | use Carp; | ||
| 13 | use Scalar::Util qw(weaken); | ||
| 14 | use Try::Tiny; | ||
| 15 | |||
| 16 | # AccessGuard is actually a singleton - there can't be two different guards, since process can't have two euids. | ||
| 17 | # So we keep weakref to any created AccessGuard. | ||
| 18 | my $ag_ref; | ||
| 19 | |||
| 20 | |||
| 21 | sub new { | ||
| 22 | my $class = shift; | ||
| 23 | my ($credentials) = validate_pos(@_, { isa => 'Ubic::Credentials' }); | ||
| 24 | |||
| 25 | if ($ag_ref) { | ||
| 26 | # oops, another AccessGuard already exists | ||
| 27 | my $ag = $$ag_ref; | ||
| 28 | if ($ag->{credentials}->eq($credentials)) { | ||
| 29 | # new guard is the same as old guard | ||
| 30 | return $ag; | ||
| 31 | } | ||
| 32 | else { | ||
| 33 | croak "Can't create AccessGuard for ".$credentials->as_string.", there is already another AccessGuard for ".$ag->{credentials}->as_string; | ||
| 34 | } | ||
| 35 | } | ||
| 36 | |||
| 37 | my $self = bless { | ||
| 38 | credentials => $credentials, | ||
| 39 | } => $class; | ||
| 40 | |||
| 41 | try { | ||
| 42 | $credentials->set_effective; | ||
| 43 | } | ||
| 44 | catch { | ||
| 45 | die result('unknown', "$_"); | ||
| 46 | }; | ||
| 47 | |||
| 48 | $ag_ref = \$self; | ||
| 49 | weaken($ag_ref); | ||
| 50 | |||
| 51 | return $self; | ||
| 52 | } | ||
| 53 | |||
| 54 | sub DESTROY { | ||
| 55 | my $self = shift; | ||
| 56 | local $@; | ||
| 57 | |||
| 58 | $self->{credentials}->reset_effective; | ||
| 59 | } | ||
| 60 | |||
| 61 | |||
| 62 | 1; | ||
| 63 | |||
| 64 | __END__ |