Statistics
| Branch: | Tag: | Revision:

root / image_creator / os_type / freebsd.py @ f953c647

History | View | Annotate | Download (5.3 kB)

1
# -*- coding: utf-8 -*-
2
#
3
# Copyright 2012 GRNET S.A. All rights reserved.
4
#
5
# Redistribution and use in source and binary forms, with or
6
# without modification, are permitted provided that the following
7
# conditions are met:
8
#
9
#   1. Redistributions of source code must retain the above
10
#      copyright notice, this list of conditions and the following
11
#      disclaimer.
12
#
13
#   2. Redistributions in binary form must reproduce the above
14
#      copyright notice, this list of conditions and the following
15
#      disclaimer in the documentation and/or other materials
16
#      provided with the distribution.
17
#
18
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
# POSSIBILITY OF SUCH DAMAGE.
30
#
31
# The views and conclusions contained in the software and
32
# documentation are those of the authors and should not be
33
# interpreted as representing official policies, either expressed
34
# or implied, of GRNET S.A.
35

    
36
"""This module hosts OS-specific code for FreeBSD."""
37

    
38
from image_creator.os_type.unix import Unix, sysprep
39

    
40
import re
41

    
42

    
43
class Freebsd(Unix):
44
    """OS class for FreeBSD Unix-like os"""
45

    
46
    @sysprep("Cleaning up passwords & locking all user accounts")
47
    def cleanup_password(self):
48
        """Remove all passwords and lock all user accounts"""
49

    
50
        master_passwd = []
51

    
52
        for line in self.image.g.cat('/etc/master.passwd').splitlines():
53

    
54
            # Check for empty or comment lines
55
            if len(line.split('#')[0]) == 0:
56
                master_passwd.append(line)
57
                continue
58

    
59
            fields = line.split(':')
60
            if fields[1] not in ('*', '!'):
61
                fields[1] = '!'
62

    
63
            master_passwd.append(":".join(fields))
64

    
65
        self.image.g.write(
66
            '/etc/master.passwd', "\n".join(master_passwd) + '\n')
67

    
68
        # Make sure no one can login on the system
69
        self.image.g.rm_rf('/etc/spwd.db')
70

    
71
    def _do_collect_metadata(self):
72
        """Collect metadata about the OS"""
73
        super(Freebsd, self)._do_collect_metadata()
74
        self.meta["USERS"] = " ".join(self._get_passworded_users())
75

    
76
        #The original product name key is long and ugly
77
        self.meta['DESCRIPTION'] = \
78
            self.meta['DESCRIPTION'].split('#')[0].strip()
79

    
80
        # Delete the USERS metadata if empty
81
        if not len(self.meta['USERS']):
82
            self.out.warn("No passworded users found!")
83
            del self.meta['USERS']
84

    
85
    def _do_inspect(self):
86
        """Run various diagnostics to check if media is supported"""
87

    
88
        self.out.output('Checking partition table type...', False)
89
        ptype = self.image.g.part_get_parttype(self.image.guestfs_device)
90
        if ptype != 'gpt':
91
            self.out.warn("partition table type is: `%s'" % ptype)
92
            self.image.set_unsupported(
93
                'On FreeBSD only GUID partition tables are supported')
94
        else:
95
            self.out.success(ptype)
96

    
97
    def _get_passworded_users(self):
98
        """Returns a list of non-locked user accounts"""
99
        users = []
100
        regexp = re.compile(
101
            '^([^:]+):((?:![^:]+)|(?:[^!*][^:]+)|):(?:[^:]*:){7}(?:[^:]*)'
102
        )
103

    
104
        for line in self.image.g.cat('/etc/master.passwd').splitlines():
105
            line = line.split('#')[0]
106
            match = regexp.match(line)
107
            if not match:
108
                continue
109

    
110
            user, passwd = match.groups()
111
            if len(passwd) > 0 and passwd[0] == '!':
112
                self.out.warn("Ignoring locked %s account." % user)
113
            else:
114
                users.append(user)
115

    
116
        return users
117

    
118
    def _do_mount(self, readonly):
119
        """Mount partitions in the correct order"""
120

    
121
        critical_mpoints = ('/', '/etc', '/root', '/home', '/var')
122

    
123
        # libguestfs can't handle correct freebsd partitions on a GUID
124
        # Partition Table. We have to do the translation to linux device names
125
        # ourselves
126
        guid_device = re.compile(r'^/dev/((?:ada)|(?:vtbd))(\d+)p(\d+)$')
127

    
128
        mopts = "ufstype=ufs2,%s" % ('ro' if readonly else 'rw')
129
        for mp, dev in self._mountpoints():
130
            match = guid_device.match(dev)
131
            if match:
132
                group2 = int(match.group(2))
133
                group3 = int(match.group(3))
134
                dev = '/dev/sd%c%d' % (chr(ord('a') + group2), group3)
135
            try:
136
                self.image.g.mount_vfs(mopts, 'ufs', dev, mp)
137
            except RuntimeError as msg:
138
                if mp in critical_mpoints:
139
                    self.out.warn('unable to mount %s. Reason: %s' % (mp, msg))
140
                    return False
141
                else:
142
                    self.out.warn('%s (ignored)' % msg)
143

    
144
        return True
145

    
146
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :