~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to lib/common/makeuser.py

  • Committer: Matt Giuca
  • Date: 2009-03-24 06:50:39 UTC
  • mto: This revision was merged to the branch mainline in revision 1322.
  • Revision ID: matt.giuca@gmail.com-20090324065039-5c6xkjeb8x2f5d01
doc/conf.py: Renamed project from "ivle" to "IVLE". (Turns out this is a
    friendly name).

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# IVLE - Informatics Virtual Learning Environment
2
 
# Copyright (C) 2007-2008 The University of Melbourne
3
 
#
4
 
# This program is free software; you can redistribute it and/or modify
5
 
# it under the terms of the GNU General Public License as published by
6
 
# the Free Software Foundation; either version 2 of the License, or
7
 
# (at your option) any later version.
8
 
#
9
 
# This program is distributed in the hope that it will be useful,
10
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 
# GNU General Public License for more details.
13
 
#
14
 
# You should have received a copy of the GNU General Public License
15
 
# along with this program; if not, write to the Free Software
16
 
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
 
 
18
 
# Module: MakeUser
19
 
# Author: Matt Giuca
20
 
# Date:   1/2/2008
21
 
 
22
 
# Allows creation of users. This sets up the following:
23
 
# * User's jail and home directory within the jail.
24
 
# * Subversion repository (TODO)
25
 
# * Check out Subversion workspace into jail (TODO)
26
 
# * Database details for user
27
 
# * Unix user account
28
 
 
29
 
# TODO: Sanitize login name and other fields.
30
 
# Users must not be called "temp" or "template".
31
 
 
32
 
# TODO: When creating a new home directory, chown it to its owner
33
 
 
34
 
import os
35
 
import stat
36
 
import shutil
37
 
import warnings
38
 
 
39
 
import conf
40
 
import db
41
 
 
42
 
def make_jail(username, uid, force=True):
43
 
    """Creates a new user's jail space, in the jail directory as configured in
44
 
    conf.py.
45
 
 
46
 
    This expects there to be a "template" directory within the jail root which
47
 
    contains all the files for a sample student jail. It creates the student's
48
 
    directory in the jail root, by making a hard-link copy of every file in the
49
 
    template directory, recursively.
50
 
 
51
 
    Returns the path to the user's home directory.
52
 
 
53
 
    Chowns the user's directory within the jail to the given UID.
54
 
 
55
 
    Note: This takes separate username and uid arguments. The UID need not
56
 
    *necessarily* correspond to a Unix username at all, if all you are
57
 
    planning to do is setuid to it. This allows the caller the freedom of
58
 
    deciding the binding between username and uid, if any.
59
 
 
60
 
    force: If false, exception if jail already exists for this user.
61
 
    If true (default), overwrites it, but preserves home directory.
62
 
    """
63
 
    # MUST run as root or some of this may fail
64
 
    if os.getuid() != 0:
65
 
        raise Exception("Must run make_jail as root")
66
 
    
67
 
    templatedir = os.path.join(conf.jail_base, 'template')
68
 
    if not os.path.isdir(templatedir):
69
 
        raise Exception("Template jail directory does not exist: " +
70
 
            templatedir)
71
 
    # tempdir is for putting backup homes in
72
 
    tempdir = os.path.join(conf.jail_base, 'temp')
73
 
    if not os.path.exists(tempdir):
74
 
        os.makedirs(tempdir)
75
 
    elif not os.path.isdir(tempdir):
76
 
        os.unlink(tempdir)
77
 
        os.mkdir(tempdir)
78
 
    userdir = os.path.join(conf.jail_base, username)
79
 
    homedir = os.path.join(userdir, 'home')
80
 
 
81
 
    if os.path.exists(userdir):
82
 
        if not force:
83
 
            raise Exception("User's jail already exists")
84
 
        # User jail already exists. Blow it away but preserve their home
85
 
        # directory.
86
 
        # Ignore warnings about the use of tmpnam
87
 
        warnings.simplefilter('ignore')
88
 
        homebackup = os.tempnam(tempdir)
89
 
        warnings.resetwarnings()
90
 
        # Note: shutil.move does not behave like "mv" - it does not put a file
91
 
        # into a directory if it already exists, just fails. Therefore it is
92
 
        # not susceptible to tmpnam symlink attack.
93
 
        shutil.move(homedir, homebackup)
94
 
        try:
95
 
            # Any errors that occur after making the backup will be caught and
96
 
            # the backup will be un-made.
97
 
            # XXX This will still leave the user's jail in an unusable state,
98
 
            # but at least they won't lose their files.
99
 
            shutil.rmtree(userdir)
100
 
 
101
 
            # Hard-link (copy aliasing) the entire tree over
102
 
            linktree(templatedir, userdir)
103
 
        finally:
104
 
            # Set up the user's home directory (restore backup)
105
 
            # First make sure the directory is empty and its parent exists
106
 
            try:
107
 
                shutil.rmtree(homedir)
108
 
            except:
109
 
                pass
110
 
            # XXX If this fails the user's directory will be lost (in the temp
111
 
            # directory). But it shouldn't fail as homedir should not exist.
112
 
            os.makedirs(homedir)
113
 
            shutil.move(homebackup, homedir)
114
 
        return os.path.join(homedir, username)
115
 
    else:
116
 
        # No user jail exists
117
 
        # Hard-link (copy aliasing) the entire tree over
118
 
        linktree(templatedir, userdir)
119
 
 
120
 
        # Set up the user's home directory
121
 
        userhomedir = os.path.join(homedir, username)
122
 
        os.mkdir(userhomedir)
123
 
        # Chown (and set the GID to the same as the UID).
124
 
        os.chown(userhomedir, uid, uid)
125
 
        # Chmod to rwx------ (700)
126
 
        os.chmod(userhomedir, stat.S_IRWXU)
127
 
        return userhomedir
128
 
 
129
 
def linktree(src, dst):
130
 
    """Recursively hard-link a directory tree using os.link().
131
 
 
132
 
    The destination directory must not already exist.
133
 
    If exception(s) occur, an Error is raised with a list of reasons.
134
 
 
135
 
    Symlinks are preserved (in fact, hard links are created which point to the
136
 
    symlinks).
137
 
 
138
 
    Code heavily based upon shutil.copytree from Python 2.5 library.
139
 
    """
140
 
    names = os.listdir(src)
141
 
    os.makedirs(dst)
142
 
    errors = []
143
 
    for name in names:
144
 
        srcname = os.path.join(src, name)
145
 
        dstname = os.path.join(dst, name)
146
 
        try:
147
 
            if os.path.isdir(srcname):
148
 
                linktree(srcname, dstname)
149
 
            else:
150
 
                os.link(srcname, dstname)
151
 
            # XXX What about devices, sockets etc.?
152
 
        except (IOError, os.error), why:
153
 
            errors.append((srcname, dstname, str(why)))
154
 
        # catch the Error from the recursive copytree so that we can
155
 
        # continue with other files
156
 
        except Exception, err:
157
 
            errors.append(err.args[0])
158
 
    try:
159
 
        shutil.copystat(src, dst)
160
 
    except WindowsError:
161
 
        # can't copy file access times on Windows
162
 
        pass
163
 
    except OSError, why:
164
 
        errors.extend((src, dst, str(why)))
165
 
    if errors:
166
 
        raise Exception, errors
167
 
 
168
 
def make_user_db(login, uid, password, nick, fullname, rolenm, studentid,
169
 
    force=True):
170
 
    """Creates a user's entry in the database, filling in all the fields.
171
 
    If force is False, throws an exception if the user already exists.
172
 
    If True, overwrites the user's entry in the DB.
173
 
    """
174
 
    dbconn = db.DB()
175
 
    if force:
176
 
        # Delete user if it exists
177
 
        try:
178
 
            dbconn.delete_user(login)
179
 
        except:
180
 
            pass
181
 
    dbconn.create_user(login, uid, password, nick, fullname, rolenm,
182
 
        studentid)
183
 
    dbconn.close()