1# Copyright 2007 Google Inc.
2#
3# This program is free software; you can redistribute it and/or
4# modify it under the terms of the GNU General Public License
5# as published by the Free Software Foundation; either version 2
6# of the License, or (at your option) any later version.
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with this program; if not, write to the Free Software Foundation,
15# Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
16"""An implementation of a passwd map for nsscache.
17
18PasswdMap:  An implementation of NSS passwd maps based on the Map
19class.
20
21PasswdMapEntry:  A passwd map entry based on the MapEntry class.
22"""
23
24__author__ = 'vasilios@google.com (Vasilios Hoffman)'
25
26from nss_cache.maps import maps
27
28
29class PasswdMap(maps.Map):
30    """This class represents an NSS passwd map.
31
32    Map data is stored as a list of MapEntry objects, see the abstract
33    class Map.
34    """
35
36    def Add(self, entry):
37        """Add a new object, verify it is a PasswdMapEntry instance.
38
39        Args:
40          entry: A PasswdMapEntry instance.
41
42        Returns:
43          True if added successfully, False otherwise.
44
45        Raises:
46          TypeError: The argument is of the wrong type.
47        """
48        if not isinstance(entry, PasswdMapEntry):
49            raise TypeError
50        return super(PasswdMap, self).Add(entry)
51
52
53class PasswdMapEntry(maps.MapEntry):
54    """This class represents NSS passwd map entries."""
55    # Using slots saves us over 2x memory on large maps.
56    __slots__ = ('name', 'uid', 'gid', 'passwd', 'gecos', 'dir', 'shell')
57    _KEY = 'name'
58    _ATTRS = ('name', 'uid', 'gid', 'passwd', 'gecos', 'dir', 'shell')
59
60    def __init__(self, data=None):
61        """Construct a PasswdMapEntry, setting reasonable defaults."""
62        self.name = None
63        self.uid = None
64        self.gid = None
65        self.passwd = None
66        self.gecos = None
67        self.dir = None
68        self.shell = None
69
70        super(PasswdMapEntry, self).__init__(data)
71
72        # Seed data with defaults if still empty
73        if self.passwd is None:
74            self.passwd = 'x'
75        if self.gecos is None:
76            self.gecos = ''
77        if self.dir is None:
78            self.dir = ''
79        if self.shell is None:
80            self.shell = ''
81