xref: /openbsd/usr.sbin/pkg_add/OpenBSD/IdCache.pm (revision e5dd7070)
1# ex:ts=8 sw=4:
2# $OpenBSD: IdCache.pm,v 1.10 2010/12/24 09:04:14 espie Exp $
3#
4# Copyright (c) 2002-2005 Marc Espie <espie@openbsd.org>
5#
6# Permission to use, copy, modify, and distribute this software for any
7# purpose with or without fee is hereby granted, provided that the above
8# copyright notice and this permission notice appear in all copies.
9#
10# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
17use strict;
18use warnings;
19
20package OpenBSD::SimpleIdCache;
21sub new
22{
23	my $class = shift;
24	bless {}, $class;
25}
26
27sub lookup
28{
29	my ($self, $name, $default) = @_;
30	my $r;
31
32	if (defined $self->{$name}) {
33		$r = $self->{$name};
34	} else {
35		$r = $self->convert($name);
36		if (!defined $r) {
37			$r = $default;
38		}
39		$self->{$name} = $r;
40	}
41	return $r;
42}
43
44
45package OpenBSD::IdCache;
46our @ISA=qw(OpenBSD::SimpleIdCache);
47
48sub lookup
49{
50	my ($self, $name, $default) = @_;
51
52	if ($name =~ m/^\d+$/o) {
53		return $name;
54	} else {
55		return $self->SUPER::lookup($name, $default);
56	}
57}
58
59package OpenBSD::UidCache;
60our @ISA=qw(OpenBSD::IdCache);
61
62sub convert
63{
64	my @entry = getpwnam($_[1]);
65	return @entry == 0 ? undef : $entry[2];
66}
67
68package OpenBSD::GidCache;
69our @ISA=qw(OpenBSD::IdCache);
70
71sub convert
72{
73	my @entry = getgrnam($_[1]);
74	return @entry == 0 ? undef : $entry[2];
75}
76
77package OpenBSD::UnameCache;
78our @ISA=qw(OpenBSD::SimpleIdCache);
79
80sub convert
81{
82	return getpwuid($_[1]);
83}
84
85package OpenBSD::GnameCache;
86our @ISA=qw(OpenBSD::SimpleIdCache);
87
88sub convert
89{
90	return getgrgid($_[1]);
91}
92
931;
94