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

« back to all changes in this revision

Viewing changes to setup.py

  • Committer: dcoles
  • Date: 2008-03-09 02:34:46 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:671
forum: Now uses a unique secret generated at './setup config' time for shared secret

setup.py: Generate and write forum_secret to config.py and config.php
w/p/p/i/session.php: Use forum_secret from config.php and some code cleaning
l/c/forumutil.py: Use config.py to get forum_secret to make HMAC 

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
# Date:   12/12/2007
22
22
 
23
23
# This is a command-line application, for use by the administrator.
24
 
# This program is a frontend for the modules in the setup packages that 
25
 
# build and install IVLE in separate steps.
 
24
# This program configures, builds and installs IVLE in three separate steps.
26
25
# It is called with at least one argument, which specifies which operation to
27
26
# take.
28
27
 
 
28
# setup.py listmake (for developer use only)
 
29
# Recurses through the source tree and builds a list of all files which should
 
30
# be copied upon installation. This should be run by the developer before
 
31
# cutting a distribution, and the listfile it generates should be included in
 
32
# the distribution, avoiding the administrator having to run it.
 
33
 
 
34
# setup.py config [args]
 
35
# Configures IVLE with machine-specific details, most notably, various paths.
 
36
# Either prompts the administrator for these details or accepts them as
 
37
# command-line args.
 
38
# Creates lib/conf/conf.py and trampoline/conf.h.
 
39
 
 
40
# setup.py build
 
41
# Compiles all files and sets up a jail template in the source directory.
 
42
# Details:
 
43
# Compiles (GCC) trampoline/trampoline.c to trampoline/trampoline.
 
44
# Creates jail/.
 
45
# Creates standard subdirs inside the jail, eg bin, opt, home, tmp.
 
46
# Copies console/ to a location within the jail.
 
47
# Copies OS programs and files to corresponding locations within the jail
 
48
#   (eg. python and Python libs, ld.so, etc).
 
49
# Generates .pyc files for all the IVLE .py files.
 
50
 
 
51
# setup.py install [--nojail] [--dry|n]
 
52
# (Requires root)
 
53
# Create target install directory ($target).
 
54
# Create $target/bin.
 
55
# Copy trampoline/trampoline to $target/bin.
 
56
# chown and chmod the installed trampoline.
 
57
# Copy www/ to $target.
 
58
# Copy jail/ to jails template directory (unless --nojail specified).
 
59
 
 
60
import os
 
61
import stat
 
62
import shutil
29
63
import sys
30
 
import setup.build
31
 
import setup.install
 
64
import getopt
 
65
import string
 
66
import errno
 
67
import mimetypes
 
68
import compileall
 
69
import getopt
 
70
import hashlib
 
71
import uuid
 
72
 
 
73
# Import modules from the website is tricky since they're in the www
 
74
# directory.
 
75
sys.path.append(os.path.join(os.getcwd(), 'lib'))
 
76
import conf
 
77
import common.makeuser
 
78
 
 
79
# Determine which Python version (2.4 or 2.5, for example) we are running,
 
80
# and use that as the filename to the Python directory.
 
81
# Just get the first 3 characters of sys.version.
 
82
PYTHON_VERSION = sys.version[0:3]
 
83
 
 
84
# Operating system files to copy over into the jail.
 
85
# These will be copied from the given place on the OS file system into the
 
86
# same place within the jail.
 
87
JAIL_FILES = [
 
88
    '/lib/ld-linux.so.2',
 
89
    '/lib/tls/i686/cmov/libc.so.6',
 
90
    '/lib/tls/i686/cmov/libdl.so.2',
 
91
    '/lib/tls/i686/cmov/libm.so.6',
 
92
    '/lib/tls/i686/cmov/libpthread.so.0',
 
93
    '/lib/tls/i686/cmov/libutil.so.1',
 
94
    '/etc/ld.so.conf',
 
95
    '/etc/ld.so.cache',
 
96
    # These 2 files do not exist in Ubuntu
 
97
    #'/etc/ld.so.preload',
 
98
    #'/etc/ld.so.nohwcap',
 
99
    # UNIX commands
 
100
    '/usr/bin/strace',
 
101
    '/bin/ls',
 
102
    '/bin/echo',
 
103
    # Needed by python
 
104
    '/usr/bin/python%s' % PYTHON_VERSION,
 
105
    # Needed by fileservice
 
106
    '/lib/libcom_err.so.2',
 
107
    '/lib/libcrypt.so.1',
 
108
    '/lib/libkeyutils.so.1',
 
109
    '/lib/libresolv.so.2',
 
110
    '/lib/librt.so.1',
 
111
    '/lib/libuuid.so.1',
 
112
    '/usr/lib/libapr-1.so.0',
 
113
    '/usr/lib/libaprutil-1.so.0',
 
114
    '/usr/lib/libdb-4.4.so',
 
115
    '/usr/lib/libexpat.so.1',
 
116
    '/usr/lib/libgcrypt.so.11',
 
117
    '/usr/lib/libgnutls.so.13',
 
118
    '/usr/lib/libgpg-error.so.0',
 
119
    '/usr/lib/libgssapi_krb5.so.2',
 
120
    '/usr/lib/libk5crypto.so.3',
 
121
    '/usr/lib/libkrb5.so.3',
 
122
    '/usr/lib/libkrb5support.so.0',
 
123
    '/usr/lib/liblber.so.2',
 
124
    '/usr/lib/libldap_r.so.2',
 
125
    '/usr/lib/libneon.so.26',
 
126
    '/usr/lib/libpq.so.5',
 
127
    '/usr/lib/libsasl2.so.2',
 
128
    '/usr/lib/libsqlite3.so.0',
 
129
    '/usr/lib/libsvn_client-1.so.1',
 
130
    '/usr/lib/libsvn_delta-1.so.1',
 
131
    '/usr/lib/libsvn_diff-1.so.1',
 
132
    '/usr/lib/libsvn_fs-1.so.1',
 
133
    '/usr/lib/libsvn_fs_base-1.so.1',
 
134
    '/usr/lib/libsvn_fs_fs-1.so.1',
 
135
    '/usr/lib/libsvn_ra-1.so.1',
 
136
    '/usr/lib/libsvn_ra_dav-1.so.1',
 
137
    '/usr/lib/libsvn_ra_local-1.so.1',
 
138
    '/usr/lib/libsvn_ra_svn-1.so.1',
 
139
    '/usr/lib/libsvn_repos-1.so.1',
 
140
    '/usr/lib/libsvn_subr-1.so.1',
 
141
    '/usr/lib/libsvn_wc-1.so.1',
 
142
    '/usr/lib/libtasn1.so.3',
 
143
    '/usr/lib/libxml2.so.2',
 
144
    # Needed by matplotlib
 
145
    '/usr/lib/i686/cmov/libssl.so.0.9.8',
 
146
    '/usr/lib/i686/cmov/libcrypto.so.0.9.8',
 
147
    '/lib/tls/i686/cmov/libnsl.so.1',
 
148
    '/usr/lib/libz.so.1',
 
149
    '/usr/lib/atlas/liblapack.so.3',
 
150
    '/usr/lib/atlas/libblas.so.3',
 
151
    '/usr/lib/libg2c.so.0',
 
152
    '/usr/lib/libstdc++.so.6',
 
153
    '/usr/lib/libfreetype.so.6',
 
154
    '/usr/lib/libpng12.so.0',
 
155
    '/usr/lib/libBLT.2.4.so.8.4',
 
156
    '/usr/lib/libtk8.4.so.0',
 
157
    '/usr/lib/libtcl8.4.so.0',
 
158
    '/usr/lib/tcl8.4/init.tcl',
 
159
    '/usr/lib/libX11.so.6',
 
160
    '/usr/lib/libXau.so.6',
 
161
    '/usr/lib/libXdmcp.so.6',
 
162
    '/lib/libgcc_s.so.1',
 
163
    '/etc/matplotlibrc',
 
164
    # Needed for resolv
 
165
    '/lib/libnss_dns.so.2',
 
166
    #'/lib/libnss_mdns4.so',
 
167
    '/etc/hosts',
 
168
    '/etc/resolv.conf',
 
169
    #'/etc/hosts.conf',
 
170
    #'/etc/hostname',
 
171
    '/etc/nsswitch.conf',
 
172
    '/lib/libnss_files.so.2',
 
173
]
 
174
# Symlinks to make within the jail. Src mapped to dst.
 
175
JAIL_LINKS = {
 
176
    'python%s' % PYTHON_VERSION: 'jail/usr/bin/python',
 
177
}
 
178
# Trees to copy. Src mapped to dst (these will be passed to action_copytree).
 
179
JAIL_COPYTREES = {
 
180
    '/usr/lib/python%s' % PYTHON_VERSION:
 
181
        'jail/usr/lib/python%s' % PYTHON_VERSION,
 
182
    '/usr/share/matplotlib': 'jail/usr/share/matplotlib',
 
183
    '/etc/ld.so.conf.d': 'jail/etc/ld.so.conf.d',
 
184
}
 
185
 
 
186
class ConfigOption:
 
187
    """A configuration option; one of the things written to conf.py."""
 
188
    def __init__(self, option_name, default, prompt, comment):
 
189
        """Creates a configuration option.
 
190
        option_name: Name of the variable in conf.py. Also name of the
 
191
            command-line argument to setup.py conf.
 
192
        default: Default value for this variable.
 
193
        prompt: (Short) string presented during the interactive prompt in
 
194
            setup.py conf.
 
195
        comment: (Long) comment string stored in conf.py. Each line of this
 
196
            string should begin with a '#'.
 
197
        """
 
198
        self.option_name = option_name
 
199
        self.default = default
 
200
        self.prompt = prompt
 
201
        self.comment = comment
 
202
 
 
203
# Configuration options, defaults and descriptions
 
204
config_options = []
 
205
config_options.append(ConfigOption("root_dir", "/",
 
206
    """Root directory where IVLE is located (in URL space):""",
 
207
    """
 
208
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
 
209
# with this).
 
210
# eg. "/" or "/ivle"."""))
 
211
config_options.append(ConfigOption("ivle_install_dir", "/opt/ivle",
 
212
    'Root directory where IVLE will be installed (on the local file '
 
213
    'system):',
 
214
    """
 
215
# In the local file system, where IVLE is actually installed.
 
216
# This directory should contain the "www" and "bin" directories."""))
 
217
config_options.append(ConfigOption("jail_base", "/home/informatics/jails",
 
218
    """Location of Directories
 
219
=======================
 
220
Root directory where the jails (containing user files) are stored
 
221
(on the local file system):""",
 
222
    """
 
223
# In the local file system, where are the student/user file spaces located.
 
224
# The user jails are expected to be located immediately in subdirectories of
 
225
# this location."""))
 
226
config_options.append(ConfigOption("subjects_base",
 
227
    "/home/informatics/subjects",
 
228
    """Root directory where the subject directories (containing worksheets
 
229
and other per-subject files) are stored (on the local file system):""",
 
230
    """
 
231
# In the local file system, where are the per-subject file spaces located.
 
232
# The individual subject directories are expected to be located immediately
 
233
# in subdirectories of this location."""))
 
234
config_options.append(ConfigOption("exercises_base",
 
235
    "/home/informatics/exercises",
 
236
    """Root directory where the exercise directories (containing
 
237
subject-independent exercise sheets) are stored (on the local file
 
238
system):""",
 
239
    """
 
240
# In the local file system, where are the subject-independent exercise sheet
 
241
# file spaces located."""))
 
242
config_options.append(ConfigOption("public_host", "public.localhost",
 
243
    """Hostname which will cause the server to go into "public mode",
 
244
providing login-free access to student's published work:""",
 
245
    """
 
246
# The server goes into "public mode" if the browser sends a request with this
 
247
# host. This is for security reasons - we only serve public student files on a
 
248
# separate domain to the main IVLE site.
 
249
# Public mode does not use cookies, and serves only public content.
 
250
# Private mode (normal mode) requires login, and only serves files relevant to
 
251
# the logged-in user."""))
 
252
config_options.append(ConfigOption("allowed_uids", "33",
 
253
    """UID of the web server process which will run IVLE.
 
254
Only this user may execute the trampoline. May specify multiple users as
 
255
a comma-separated list.
 
256
    (eg. "1002,78")""",
 
257
    """
 
258
# The User-ID of the web server process which will run IVLE, and any other
 
259
# users who are allowed to run the trampoline. This is stores as a string of
 
260
# comma-separated integers, simply because it is not used within Python, only
 
261
# used by the setup program to write to conf.h (see setup.py config)."""))
 
262
config_options.append(ConfigOption("db_host", "localhost",
 
263
    """PostgreSQL Database config
 
264
==========================
 
265
Hostname of the DB server:""",
 
266
    """
 
267
### PostgreSQL Database config ###
 
268
# Database server hostname"""))
 
269
config_options.append(ConfigOption("db_port", "5432",
 
270
    """Port of the DB server:""",
 
271
    """
 
272
# Database server port"""))
 
273
config_options.append(ConfigOption("db_dbname", "ivle",
 
274
    """Database name:""",
 
275
    """
 
276
# Database name"""))
 
277
config_options.append(ConfigOption("db_forumdbname", "ivle_forum",
 
278
    """Forum Database name:""",
 
279
    """
 
280
# Forum Database name"""))
 
281
config_options.append(ConfigOption("db_user", "postgres",
 
282
    """Username for DB server login:""",
 
283
    """
 
284
# Database username"""))
 
285
config_options.append(ConfigOption("db_password", "",
 
286
    """Password for DB server login:
 
287
    (Caution: This password is stored in plaintext in lib/conf/conf.py)""",
 
288
    """
 
289
# Database password"""))
 
290
config_options.append(ConfigOption("auth_modules", "ldap_auth",
 
291
    """Authentication config
 
292
=====================
 
293
Comma-separated list of authentication modules. Only "ldap" is available
 
294
by default.""",
 
295
    """
 
296
# Comma-separated list of authentication modules.
 
297
# These refer to importable Python modules in the www/auth directory.
 
298
# Modules "ldap" and "guest" are available in the source tree, but
 
299
# other modules may be plugged in to auth against organisation-specific
 
300
# auth backends."""))
 
301
config_options.append(ConfigOption("ldap_url", "ldaps://www.example.com",
 
302
    """(LDAP options are only relevant if "ldap" is included in the list of
 
303
auth modules).
 
304
URL for LDAP authentication server:""",
 
305
    """
 
306
# URL for LDAP authentication server"""))
 
307
config_options.append(ConfigOption("ldap_format_string",
 
308
    "uid=%s,ou=users,o=example",
 
309
    """Format string for LDAP auth request:
 
310
    (Must contain a single "%s" for the user's login name)""",
 
311
    """
 
312
# Format string for LDAP auth request
 
313
# (Must contain a single "%s" for the user's login name)"""))
 
314
config_options.append(ConfigOption("svn_addr", "http://svn.localhost/",
 
315
    """Subversion config
 
316
=================
 
317
The base url for accessing subversion repositories:""",
 
318
    """
 
319
# The base url for accessing subversion repositories."""))
 
320
config_options.append(ConfigOption("svn_conf", "/opt/ivle/svn/svn.conf",
 
321
    """The location of the subversion configuration file used by apache
 
322
to host the user repositories:""",
 
323
    """
 
324
# The location of the subversion configuration file used by
 
325
# apache to host the user repositories."""))
 
326
config_options.append(ConfigOption("svn_repo_path", "/home/informatics/repositories",
 
327
    """The root directory for the subversion repositories:""",
 
328
    """
 
329
# The root directory for the subversion repositories."""))
 
330
config_options.append(ConfigOption("svn_auth_ivle", "/opt/ivle/svn/ivle.auth",
 
331
    """The location of the password file used to authenticate users
 
332
of the subversion repository from the ivle server:""",
 
333
    """
 
334
# The location of the password file used to authenticate users
 
335
# of the subversion repository from the ivle server."""))
 
336
config_options.append(ConfigOption("svn_auth_local", "/opt/ivle/svn/local.auth",
 
337
    """The location of the password file used to authenticate local users
 
338
of the subversion repository:""",
 
339
    """
 
340
# The location of the password file used to authenticate local users
 
341
# of the subversion repository."""))
 
342
config_options.append(ConfigOption("usrmgt_host", "localhost",
 
343
    """User Management Server config
 
344
============================
 
345
The hostname where the usrmgt-server runs:""",
 
346
    """
 
347
# The hostname where the usrmgt-server runs."""))
 
348
config_options.append(ConfigOption("usrmgt_port", "2178",
 
349
    """The port where the usrmgt-server runs:""",
 
350
    """
 
351
# The port where the usrmgt-server runs."""))
 
352
config_options.append(ConfigOption("usrmgt_magic", "",
 
353
    """The password for the usrmgt-server:""",
 
354
    """
 
355
# The password for the usrmgt-server."""))
 
356
 
 
357
# Try importing existing conf, but if we can't just set up defaults
 
358
# The reason for this is that these settings are used by other phases
 
359
# of setup besides conf, so we need to know them.
 
360
# Also this allows you to hit Return to accept the existing value.
 
361
try:
 
362
    confmodule = __import__("lib/conf/conf")
 
363
    for opt in config_options:
 
364
        try:
 
365
            globals()[opt.option_name] = confmodule.__dict__[opt.option_name]
 
366
        except:
 
367
            globals()[opt.option_name] = opt.default
 
368
except ImportError:
 
369
    # Just set reasonable defaults
 
370
    for opt in config_options:
 
371
        globals()[opt.option_name] = opt.default
 
372
 
 
373
# Try importing install_list, but don't fail if we can't, because listmake can
 
374
# function without it.
 
375
try:
 
376
    import install_list
 
377
except:
 
378
    pass
 
379
 
 
380
# Mime types which will automatically be placed in the list by listmake.
 
381
# Note that listmake is not intended to be run by the final user (the system
 
382
# administrator who installs this), so the developers can customize the list
 
383
# as necessary, and include it in the distribution.
 
384
listmake_mimetypes = ['text/x-python', 'text/html',
 
385
    'application/x-javascript', 'application/javascript',
 
386
    'text/css', 'image/png', 'image/gif', 'application/xml']
 
387
 
 
388
# Main function skeleton from Guido van Rossum
 
389
# http://www.artima.com/weblogs/viewpost.jsp?thread=4829
32
390
 
33
391
def main(argv=None):
34
392
    if argv is None:
37
395
    # Print the opening spiel including the GPL notice
38
396
 
39
397
    print """IVLE - Informatics Virtual Learning Environment Setup
40
 
Copyright (C) 2007-2009 The University of Melbourne
 
398
Copyright (C) 2007-2008 The University of Melbourne
41
399
IVLE comes with ABSOLUTELY NO WARRANTY.
42
400
This is free software, and you are welcome to redistribute it
43
401
under certain conditions. See LICENSE.txt for details.
53
411
        help([])
54
412
        return 1
55
413
 
56
 
    oper_func = call_operator(operation)
57
 
    return oper_func(argv[2:])
58
 
 
59
 
def help(args):
60
 
    if len(args)!=1:
61
 
        print """Usage: python setup.py operation [options]
62
 
Operation can be:
63
 
    help [operation]
64
 
    build
65
 
    install
66
 
 
67
 
    For help and options for a specific operation use 'help [operation]'."""
68
 
    else:
69
 
        operator = args[0]
70
 
        oper_func = call_operator(operator)
71
 
        oper_func(['operator','--help'])
72
 
 
73
 
def call_operator(operation):
 
414
    # Disallow run as root unless installing
 
415
    if (operation != 'install' and operation != 'updatejails'
 
416
        and os.geteuid() == 0):
 
417
        print >>sys.stderr, "I do not want to run this stage as root."
 
418
        print >>sys.stderr, "Please run as a normal user."
 
419
        return 1
74
420
    # Call the requested operation's function
75
421
    try:
76
422
        oper_func = {
77
423
            'help' : help,
78
 
            'build' : setup.build.build,
79
 
            'install' : setup.install.install,
 
424
            'config' : conf,
 
425
            'build' : build,
 
426
            'listmake' : listmake,
 
427
            'install' : install,
 
428
            'updatejails' : updatejails,
80
429
        }[operation]
81
430
    except KeyError:
82
431
        print >>sys.stderr, (
83
432
            """Invalid operation '%s'. Try python setup.py help."""
84
433
            % operation)
85
 
        sys.exit(1)
86
 
    return oper_func
 
434
        return 1
 
435
    return oper_func(argv[2:])
 
436
 
 
437
# Operation functions
 
438
 
 
439
def help(args):
 
440
    if args == []:
 
441
        print """Usage: python setup.py operation [args]
 
442
Operation (and args) can be:
 
443
    help [operation]
 
444
    listmake (developer use only)
 
445
    config [args]
 
446
    build
 
447
    install [--nojail] [--nosubjects] [-n|--dry]
 
448
"""
 
449
        return 1
 
450
    elif len(args) != 1:
 
451
        print """Usage: python setup.py help [operation]"""
 
452
        return 2
 
453
    else:
 
454
        operation = args[0]
 
455
 
 
456
    if operation == 'help':
 
457
        print """python setup.py help [operation]
 
458
Prints the usage message or detailed help on an operation, then exits."""
 
459
    elif operation == 'listmake':
 
460
        print """python setup.py listmake
 
461
(For developer use only)
 
462
Recurses through the source tree and builds a list of all files which should
 
463
be copied upon installation. This should be run by the developer before
 
464
cutting a distribution, and the listfile it generates should be included in
 
465
the distribution, avoiding the administrator having to run it."""
 
466
    elif operation == 'config':
 
467
        print """python setup.py config [args]
 
468
Configures IVLE with machine-specific details, most notably, various paths.
 
469
Either prompts the administrator for these details or accepts them as
 
470
command-line args. Will be interactive only if there are no arguments given.
 
471
Takes defaults from existing conf file if it exists.
 
472
 
 
473
To run IVLE out of the source directory (allowing development without having
 
474
to rebuild/install), just provide ivle_install_dir as the IVLE trunk
 
475
directory, and run build/install one time.
 
476
 
 
477
Creates lib/conf/conf.py and trampoline/conf.h.
 
478
 
 
479
Args are:"""
 
480
        for opt in config_options:
 
481
            print "    --" + opt.option_name
 
482
        print """As explained in the interactive prompt or conf.py.
 
483
"""
 
484
    elif operation == 'build':
 
485
        print """python -O setup.py build [--dry|-n]
 
486
Compiles all files and sets up a jail template in the source directory.
 
487
-O is recommended to cause compilation to be optimised.
 
488
Details:
 
489
Compiles (GCC) trampoline/trampoline.c to trampoline/trampoline.
 
490
Creates jail/.
 
491
Creates standard subdirs inside the jail, eg bin, opt, home, tmp.
 
492
Copies console/ to a location within the jail.
 
493
Copies OS programs and files to corresponding locations within the jail
 
494
  (eg. python and Python libs, ld.so, etc).
 
495
Generates .pyc or .pyo files for all the IVLE .py files.
 
496
 
 
497
--dry | -n  Print out the actions but don't do anything."""
 
498
    elif operation == 'install':
 
499
        print """sudo python setup.py install [--nojail] [--nosubjects][--dry|-n]
 
500
(Requires root)
 
501
Create target install directory ($target).
 
502
Create $target/bin.
 
503
Copy trampoline/trampoline to $target/bin.
 
504
chown and chmod the installed trampoline.
 
505
Copy www/ to $target.
 
506
Copy jail/ to jails template directory (unless --nojail specified).
 
507
Copy subjects/ to subjects directory (unless --nosubjects specified).
 
508
 
 
509
--nojail        Do not copy the jail.
 
510
--nosubjects    Do not copy the subjects and exercises directories.
 
511
--dry | -n  Print out the actions but don't do anything."""
 
512
    elif operation == 'updatejails':
 
513
        print """sudo python setup.py updatejails [--dry|-n]
 
514
(Requires root)
 
515
Copy jail/ to each subdirectory in jails directory.
 
516
 
 
517
--dry | -n  Print out the actions but don't do anything."""
 
518
    else:
 
519
        print >>sys.stderr, (
 
520
            """Invalid operation '%s'. Try python setup.py help."""
 
521
            % operation)
 
522
    return 1
 
523
 
 
524
def listmake(args):
 
525
    # We build two separate lists, by walking www and console
 
526
    list_www = build_list_py_files('www')
 
527
    list_lib = build_list_py_files('lib')
 
528
    list_subjects = build_list_py_files('subjects', no_top_level=True)
 
529
    list_exercises = build_list_py_files('exercises', no_top_level=True)
 
530
    list_scripts = [
 
531
        "scripts/python-console",
 
532
        "scripts/fileservice",
 
533
        "scripts/serveservice",
 
534
        "scripts/usrmgt-server",
 
535
        "scripts/diffservice",
 
536
    ]
 
537
    # Make sure that the files generated by conf are in the list
 
538
    # (since listmake is typically run before conf)
 
539
    if "lib/conf/conf.py" not in list_lib:
 
540
        list_lib.append("lib/conf/conf.py")
 
541
    # Write these out to a file
 
542
    cwd = os.getcwd()
 
543
    # the files that will be created/overwritten
 
544
    listfile = os.path.join(cwd, "install_list.py")
 
545
 
 
546
    try:
 
547
        file = open(listfile, "w")
 
548
 
 
549
        file.write("""# IVLE Configuration File
 
550
# install_list.py
 
551
# Provides lists of all files to be installed by `setup.py install' from
 
552
# certain directories.
 
553
# Note that any files with the given filename plus 'c' or 'o' (that is,
 
554
# compiled .pyc or .pyo files) will be copied as well.
 
555
 
 
556
# List of all installable files in www directory.
 
557
list_www = """)
 
558
        writelist_pretty(file, list_www)
 
559
        file.write("""
 
560
# List of all installable files in lib directory.
 
561
list_lib = """)
 
562
        writelist_pretty(file, list_lib)
 
563
        file.write("""
 
564
# List of all installable files in scripts directory.
 
565
list_scripts = """)
 
566
        writelist_pretty(file, list_scripts)
 
567
        file.write("""
 
568
# List of all installable files in subjects directory.
 
569
# This is to install sample subjects and material.
 
570
list_subjects = """)
 
571
        writelist_pretty(file, list_subjects)
 
572
        file.write("""
 
573
# List of all installable files in exercises directory.
 
574
# This is to install sample exercise material.
 
575
list_exercises = """)
 
576
        writelist_pretty(file, list_exercises)
 
577
 
 
578
        file.close()
 
579
    except IOError, (errno, strerror):
 
580
        print "IO error(%s): %s" % (errno, strerror)
 
581
        sys.exit(1)
 
582
 
 
583
    print "Successfully wrote install_list.py"
 
584
 
 
585
    print
 
586
    print ("You may modify the set of installable files before cutting the "
 
587
            "distribution:")
 
588
    print listfile
 
589
    print
 
590
 
 
591
    return 0
 
592
 
 
593
def build_list_py_files(dir, no_top_level=False):
 
594
    """Builds a list of all py files found in a directory and its
 
595
    subdirectories. Returns this as a list of strings.
 
596
    no_top_level=True means the file paths will not include the top-level
 
597
    directory.
 
598
    """
 
599
    pylist = []
 
600
    for (dirpath, dirnames, filenames) in os.walk(dir):
 
601
        # Exclude directories beginning with a '.' (such as '.svn')
 
602
        filter_mutate(lambda x: x[0] != '.', dirnames)
 
603
        # All *.py files are added to the list
 
604
        pylist += [os.path.join(dirpath, item) for item in filenames
 
605
            if mimetypes.guess_type(item)[0] in listmake_mimetypes]
 
606
    if no_top_level:
 
607
        for i in range(0, len(pylist)):
 
608
            _, pylist[i] = pylist[i].split(os.sep, 1)
 
609
    return pylist
 
610
 
 
611
def writelist_pretty(file, list):
 
612
    """Writes a list one element per line, to a file."""
 
613
    if list == []:
 
614
        file.write("[]\n")
 
615
    else:
 
616
        file.write('[\n')
 
617
        for elem in list:
 
618
            file.write('    %s,\n' % repr(elem))
 
619
        file.write(']\n')
 
620
 
 
621
def conf(args):
 
622
    global db_port, usrmgt_port
 
623
    # Set up some variables
 
624
 
 
625
    cwd = os.getcwd()
 
626
    # the files that will be created/overwritten
 
627
    conffile = os.path.join(cwd, "lib/conf/conf.py")
 
628
    jailconffile = os.path.join(cwd, "lib/conf/jailconf.py")
 
629
    conf_hfile = os.path.join(cwd, "trampoline/conf.h")
 
630
    phpBBconffile = os.path.join(cwd, "www/php/phpBB3/config.php")
 
631
 
 
632
    # Get command-line arguments to avoid asking questions.
 
633
 
 
634
    optnames = []
 
635
    for opt in config_options:
 
636
        optnames.append(opt.option_name + "=")
 
637
    (opts, args) = getopt.gnu_getopt(args, "", optnames)
 
638
 
 
639
    if args != []:
 
640
        print >>sys.stderr, "Invalid arguments:", string.join(args, ' ')
 
641
        return 2
 
642
 
 
643
    if opts == []:
 
644
        # Interactive mode. Prompt the user for all the values.
 
645
 
 
646
        print """This tool will create the following files:
 
647
    %s
 
648
    %s
 
649
    %s
 
650
    %s
 
651
prompting you for details about your configuration. The file will be
 
652
overwritten if it already exists. It will *not* install or deploy IVLE.
 
653
 
 
654
Please hit Ctrl+C now if you do not wish to do this.
 
655
""" % (conffile, jailconffile, conf_hfile, phpBBconffile)
 
656
 
 
657
        # Get information from the administrator
 
658
        # If EOF is encountered at any time during the questioning, just exit
 
659
        # silently
 
660
 
 
661
        for opt in config_options:
 
662
            globals()[opt.option_name] = \
 
663
                query_user(globals()[opt.option_name], opt.prompt)
 
664
    else:
 
665
        opts = dict(opts)
 
666
        # Non-interactive mode. Parse the options.
 
667
        for opt in config_options:
 
668
            if '--' + opt.option_name in opts:
 
669
                globals()[opt.option_name] = opts['--' + opt.option_name]
 
670
 
 
671
    # Error handling on input values
 
672
    try:
 
673
        allowed_uids_list = map(int, allowed_uids.split(','))
 
674
    except ValueError:
 
675
        print >>sys.stderr, (
 
676
        "Invalid UID list (%s).\n"
 
677
        "Must be a comma-separated list of integers." % allowed_uids)
 
678
        return 1
 
679
    try:
 
680
        db_port = int(db_port)
 
681
        if db_port < 0 or db_port >= 65536: raise ValueError()
 
682
    except ValueError:
 
683
        print >>sys.stderr, (
 
684
        "Invalid DB port (%s).\n"
 
685
        "Must be an integer between 0 and 65535." % repr(db_port))
 
686
        return 1
 
687
    try:
 
688
        usrmgt_port = int(usrmgt_port)
 
689
        if usrmgt_port < 0 or usrmgt_port >= 65536: raise ValueError()
 
690
    except ValueError:
 
691
        print >>sys.stderr, (
 
692
        "Invalid user management port (%s).\n"
 
693
        "Must be an integer between 0 and 65535." % repr(usrmgt_port))
 
694
        return 1
 
695
 
 
696
    # Generate the forum secret
 
697
    forum_secret = hashlib.md5(uuid.uuid4().bytes).hexdigest()
 
698
 
 
699
    # Write lib/conf/conf.py
 
700
 
 
701
    try:
 
702
        conf = open(conffile, "w")
 
703
 
 
704
        conf.write("""# IVLE Configuration File
 
705
# conf.py
 
706
# Miscellaneous application settings
 
707
 
 
708
""")
 
709
        for opt in config_options:
 
710
            conf.write('%s\n%s = %s\n' % (opt.comment, opt.option_name,
 
711
                repr(globals()[opt.option_name])))
 
712
 
 
713
        # Add the forum secret to the config file (regenerated each config)
 
714
        conf.write('forum_secret = "%s"\n' % (forum_secret))
 
715
 
 
716
        conf.close()
 
717
    except IOError, (errno, strerror):
 
718
        print "IO error(%s): %s" % (errno, strerror)
 
719
        sys.exit(1)
 
720
 
 
721
    print "Successfully wrote lib/conf/conf.py"
 
722
 
 
723
    # Write conf/jailconf.py
 
724
 
 
725
    try:
 
726
        conf = open(jailconffile, "w")
 
727
 
 
728
        # In the "in-jail" version of conf, we don't need MOST of the details
 
729
        # (it would be a security risk to have them here).
 
730
        # So we just write root_dir, and jail_base is "/".
 
731
        # (jail_base being "/" means "jail-relative" paths are relative to "/"
 
732
        # when inside the jail.)
 
733
        conf.write("""# IVLE Configuration File
 
734
# conf.py
 
735
# Miscellaneous application settings
 
736
# (User jail version)
 
737
 
 
738
 
 
739
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
 
740
# with this).
 
741
# eg. "/" or "/ivle".
 
742
root_dir = %s
 
743
 
 
744
# In the local file system, where are the student/user file spaces located.
 
745
# The user jails are expected to be located immediately in subdirectories of
 
746
# this location.
 
747
jail_base = '/'
 
748
 
 
749
# The hostname for serving publicly accessible pages
 
750
public_host = %s
 
751
""" % (repr(root_dir),repr(public_host)))
 
752
 
 
753
        conf.close()
 
754
    except IOError, (errno, strerror):
 
755
        print "IO error(%s): %s" % (errno, strerror)
 
756
        sys.exit(1)
 
757
 
 
758
    print "Successfully wrote lib/conf/jailconf.py"
 
759
 
 
760
    # Write trampoline/conf.h
 
761
 
 
762
    try:
 
763
        conf = open(conf_hfile, "w")
 
764
 
 
765
        conf.write("""/* IVLE Configuration File
 
766
 * conf.h
 
767
 * Administrator settings required by trampoline.
 
768
 * Note: trampoline will have to be rebuilt in order for changes to this file
 
769
 * to take effect.
 
770
 */
 
771
 
 
772
/* In the local file system, where are the jails located.
 
773
 * The trampoline does not allow the creation of a jail anywhere besides
 
774
 * jail_base or a subdirectory of jail_base.
 
775
 */
 
776
static const char* jail_base = "%s";
 
777
 
 
778
/* Which user IDs are allowed to run the trampoline.
 
779
 * This list should be limited to the web server user.
 
780
 * (Note that root is an implicit member of this list).
 
781
 */
 
782
static const int allowed_uids[] = { %s };
 
783
""" % (repr(jail_base)[1:-1], repr(allowed_uids_list)[1:-1]))
 
784
    # Note: The above uses PYTHON reprs, not C reprs
 
785
    # However they should be the same with the exception of the outer
 
786
    # characters, which are stripped off and replaced
 
787
 
 
788
        conf.close()
 
789
    except IOError, (errno, strerror):
 
790
        print "IO error(%s): %s" % (errno, strerror)
 
791
        sys.exit(1)
 
792
 
 
793
    print "Successfully wrote trampoline/conf.h"
 
794
 
 
795
    # Write www/php/phpBB3/config.php
 
796
 
 
797
    try:
 
798
        conf = open(phpBBconffile, "w")
 
799
        
 
800
        # php-pg work around
 
801
        if db_host == 'localhost':
 
802
            forumdb_host = '127.0.0.1'
 
803
        else:
 
804
            forumdb_host = db_host
 
805
 
 
806
        conf.write( """<?php
 
807
// phpBB 3.0.x auto-generated configuration file
 
808
// Do not change anything in this file!
 
809
$dbms = 'postgres';
 
810
$dbhost = '""" + forumdb_host + """';
 
811
$dbport = '""" + str(db_port) + """';
 
812
$dbname = '""" + db_forumdbname + """';
 
813
$dbuser = '""" + db_user + """';
 
814
$dbpasswd = '""" + db_password + """';
 
815
 
 
816
$table_prefix = 'phpbb_';
 
817
$acm_type = 'file';
 
818
$load_extensions = '';
 
819
@define('PHPBB_INSTALLED', true);
 
820
// @define('DEBUG', true);
 
821
//@define('DEBUG_EXTRA', true);
 
822
 
 
823
$forum_secret = '""" + forum_secret +"""';
 
824
?>"""   )
 
825
    
 
826
        conf.close()
 
827
    except IOError, (errno, strerror):
 
828
        print "IO error(%s): %s" % (errno, strerror)
 
829
        sys.exit(1)
 
830
 
 
831
    print "Successfully wrote www/php/phpBB3/config.php"
 
832
 
 
833
    print
 
834
    print "You may modify the configuration at any time by editing"
 
835
    print conffile
 
836
    print jailconffile
 
837
    print conf_hfile
 
838
    print phpBBconffile
 
839
    print
 
840
    return 0
 
841
 
 
842
def build(args):
 
843
    # Get "dry" variable from command line
 
844
    (opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
 
845
    opts = dict(opts)
 
846
    dry = '-n' in opts or '--dry' in opts
 
847
 
 
848
    if dry:
 
849
        print "Dry run (no actions will be executed\n"
 
850
 
 
851
    # Compile the trampoline
 
852
    curdir = os.getcwd()
 
853
    os.chdir('trampoline')
 
854
    action_runprog('make', [], dry)
 
855
    os.chdir(curdir)
 
856
 
 
857
    # Create the jail and its subdirectories
 
858
    # Note: Other subdirs will be made by copying files
 
859
    action_mkdir('jail', dry)
 
860
    action_mkdir('jail/home', dry)
 
861
    action_mkdir('jail/tmp', dry)
 
862
 
 
863
    # Chmod the tmp directory to world writable
 
864
    action_chmod_w('jail/tmp', dry)
 
865
 
 
866
    # Copy all console and operating system files into the jail
 
867
    action_copylist(install_list.list_scripts, 'jail/opt/ivle', dry)
 
868
    copy_os_files_jail(dry)
 
869
    # Chmod the python console
 
870
    action_chmod_x('jail/opt/ivle/scripts/python-console', dry)
 
871
    action_chmod_x('jail/opt/ivle/scripts/fileservice', dry)
 
872
    action_chmod_x('jail/opt/ivle/scripts/serveservice', dry)
 
873
    
 
874
    # Also copy the IVLE lib directory into the jail
 
875
    # This is necessary for running certain scripts
 
876
    action_copylist(install_list.list_lib, 'jail/opt/ivle', dry)
 
877
    # IMPORTANT: The file jail/opt/ivle/lib/conf/conf.py contains details
 
878
    # which could compromise security if left in the jail (such as the DB
 
879
    # password).
 
880
    # The "safe" version is in jailconf.py. Delete conf.py and replace it with
 
881
    # jailconf.py.
 
882
    action_copyfile('lib/conf/jailconf.py',
 
883
        'jail/opt/ivle/lib/conf/conf.py', dry)
 
884
 
 
885
    # Compile .py files into .pyc or .pyo files
 
886
    compileall.compile_dir('www', quiet=True)
 
887
    compileall.compile_dir('lib', quiet=True)
 
888
    compileall.compile_dir('scripts', quiet=True)
 
889
    compileall.compile_dir('jail/opt/ivle/lib', quiet=True)
 
890
 
 
891
    # Set up ivle.pth inside the jail
 
892
    # Need to set /opt/ivle/lib to be on the import path
 
893
    ivle_pth = \
 
894
        "jail/usr/lib/python%s/site-packages/ivle.pth" % PYTHON_VERSION
 
895
    f = open(ivle_pth, 'w')
 
896
    f.write('/opt/ivle/lib\n')
 
897
    f.close()
 
898
 
 
899
    return 0
 
900
 
 
901
def copy_os_files_jail(dry):
 
902
    """Copies necessary Operating System files from their usual locations
 
903
    into the jail/ directory of the cwd."""
 
904
    # Currently source paths are configured for Ubuntu.
 
905
    for filename in JAIL_FILES:
 
906
        copy_file_to_jail(filename, dry)
 
907
    for src, dst in JAIL_LINKS.items():
 
908
        action_symlink(src, dst, dry)
 
909
    for src, dst in JAIL_COPYTREES.items():
 
910
        action_copytree(src, dst, dry)
 
911
 
 
912
def copy_file_to_jail(src, dry):
 
913
    """Copies a single file from an absolute location into the same location
 
914
    within the jail. src must begin with a '/'. The jail will be located
 
915
    in a 'jail' subdirectory of the current path."""
 
916
    action_copyfile(src, 'jail' + src, dry)
 
917
 
 
918
def install(args):
 
919
    # Get "dry" and "nojail" variables from command line
 
920
    (opts, args) = getopt.gnu_getopt(args, "n",
 
921
        ['dry', 'nojail', 'nosubjects'])
 
922
    opts = dict(opts)
 
923
    dry = '-n' in opts or '--dry' in opts
 
924
    nojail = '--nojail' in opts
 
925
    nosubjects = '--nosubjects' in opts
 
926
 
 
927
    if dry:
 
928
        print "Dry run (no actions will be executed\n"
 
929
 
 
930
    if not dry and os.geteuid() != 0:
 
931
        print >>sys.stderr, "Must be root to run install"
 
932
        print >>sys.stderr, "(I need to chown some files)."
 
933
        return 1
 
934
 
 
935
    # Create the target (install) directory
 
936
    action_mkdir(ivle_install_dir, dry)
 
937
 
 
938
    # Create bin and copy the compiled files there
 
939
    action_mkdir(os.path.join(ivle_install_dir, 'bin'), dry)
 
940
    tramppath = os.path.join(ivle_install_dir, 'bin/trampoline')
 
941
    action_copyfile('trampoline/trampoline', tramppath, dry)
 
942
    # chown trampoline to root and set setuid bit
 
943
    action_chown_setuid(tramppath, dry)
 
944
 
 
945
    # Create a scripts directory to put the usrmgt-server in.
 
946
    action_mkdir(os.path.join(ivle_install_dir, 'scripts'), dry)
 
947
    usrmgtpath = os.path.join(ivle_install_dir, 'scripts/usrmgt-server')
 
948
    action_copyfile('scripts/usrmgt-server', usrmgtpath, dry)
 
949
    action_chmod_x(usrmgtpath, dry)
 
950
 
 
951
    # Copy the www and lib directories using the list
 
952
    action_copylist(install_list.list_www, ivle_install_dir, dry)
 
953
    action_copylist(install_list.list_lib, ivle_install_dir, dry)
 
954
    
 
955
    # Copy the php directory
 
956
    action_copytree('www/php/phpBB3',os.path.join(ivle_install_dir,'www/php/phpBB3'), 
 
957
    dry)
 
958
 
 
959
    if not nojail:
 
960
        # Copy the local jail directory built by the build action
 
961
        # to the jails template directory (it will be used as a template
 
962
        # for all the students' jails).
 
963
        action_copytree('jail', os.path.join(jail_base, 'template'), dry)
 
964
    if not nosubjects:
 
965
        # Copy the subjects and exercises directories across
 
966
        action_copylist(install_list.list_subjects, subjects_base, dry,
 
967
            srcdir="./subjects")
 
968
        action_copylist(install_list.list_exercises, exercises_base, dry,
 
969
            srcdir="./exercises")
 
970
 
 
971
    # Append IVLE path to ivle.pth in python site packages
 
972
    # (Unless it's already there)
 
973
    ivle_pth = os.path.join(sys.prefix,
 
974
        "lib/python%s/site-packages/ivle.pth" % PYTHON_VERSION)
 
975
    ivle_www = os.path.join(ivle_install_dir, "www")
 
976
    ivle_lib = os.path.join(ivle_install_dir, "lib")
 
977
    write_ivle_pth = True
 
978
    write_ivle_lib_pth = True
 
979
    try:
 
980
        file = open(ivle_pth, 'r')
 
981
        for line in file:
 
982
            if line.strip() == ivle_www:
 
983
                write_ivle_pth = False
 
984
            elif line.strip() == ivle_lib:
 
985
                write_ivle_lib_pth = False
 
986
        file.close()
 
987
    except (IOError, OSError):
 
988
        pass
 
989
    if write_ivle_pth:
 
990
        action_append(ivle_pth, ivle_www)
 
991
    if write_ivle_lib_pth:
 
992
        action_append(ivle_pth, ivle_lib)
 
993
 
 
994
    return 0
 
995
 
 
996
def updatejails(args):
 
997
    # Get "dry" variable from command line
 
998
    (opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
 
999
    opts = dict(opts)
 
1000
    dry = '-n' in opts or '--dry' in opts
 
1001
 
 
1002
    if dry:
 
1003
        print "Dry run (no actions will be executed\n"
 
1004
 
 
1005
    if not dry and os.geteuid() != 0:
 
1006
        print >>sys.stderr, "Must be root to run install"
 
1007
        print >>sys.stderr, "(I need to chown some files)."
 
1008
        return 1
 
1009
 
 
1010
    # Update the template jail directory in case it hasn't been installed
 
1011
    # recently.
 
1012
    action_copytree('jail', os.path.join(jail_base, 'template'), dry)
 
1013
 
 
1014
    # Re-link all the files in all students jails.
 
1015
    for dir in os.listdir(jail_base):
 
1016
        if dir == 'template': continue
 
1017
        # First back up the student's home directory
 
1018
        temp_home = os.tmpnam()
 
1019
        action_rename(os.path.join(jail_base, dir, 'home'), temp_home, dry)
 
1020
        # Delete the student's jail and relink the jail files
 
1021
        action_linktree(os.path.join(jail_base, 'template'),
 
1022
            os.path.join(jail_base, dir), dry)
 
1023
        # Restore the student's home directory
 
1024
        action_rename(temp_home, os.path.join(jail_base, dir, 'home'), dry)
 
1025
        # Set up the user's home directory just in case they don't have a
 
1026
        # directory for this yet
 
1027
        action_mkdir(os.path.join(jail_base, dir, 'home', dir), dry)
 
1028
 
 
1029
    return 0
 
1030
 
 
1031
# The actions call Python os functions but print actions and handle dryness.
 
1032
# May still throw os exceptions if errors occur.
 
1033
 
 
1034
class RunError:
 
1035
    """Represents an error when running a program (nonzero return)."""
 
1036
    def __init__(self, prog, retcode):
 
1037
        self.prog = prog
 
1038
        self.retcode = retcode
 
1039
    def __str__(self):
 
1040
        return str(self.prog) + " returned " + repr(self.retcode)
 
1041
 
 
1042
def action_runprog(prog, args, dry):
 
1043
    """Runs a unix program. Searches in $PATH. Synchronous (waits for the
 
1044
    program to return). Runs in the current environment. First prints the
 
1045
    action as a "bash" line.
 
1046
 
 
1047
    Throws a RunError with a retcode of the return value of the program,
 
1048
    if the program did not return 0.
 
1049
 
 
1050
    prog: String. Name of the program. (No path required, if in $PATH).
 
1051
    args: [String]. Arguments to the program.
 
1052
    dry: Bool. If True, prints but does not execute.
 
1053
    """
 
1054
    print prog, string.join(args, ' ')
 
1055
    if dry: return
 
1056
    ret = os.spawnvp(os.P_WAIT, prog, args)
 
1057
    if ret != 0:
 
1058
        raise RunError(prog, ret)
 
1059
 
 
1060
def action_remove(path, dry):
 
1061
    """Calls rmtree, deleting the target file if it exists."""
 
1062
    try:
 
1063
        print "rm -r", path
 
1064
        if not dry:
 
1065
            shutil.rmtree(path, True)
 
1066
    except OSError, (err, msg):
 
1067
        if err != errno.EEXIST:
 
1068
            raise
 
1069
        # Otherwise, didn't exist, so we don't care
 
1070
 
 
1071
def action_rename(src, dst, dry):
 
1072
    """Calls rename. Deletes the target if it already exists."""
 
1073
    action_remove(dst, dry)
 
1074
    print "mv ", src, dst
 
1075
    if dry: return
 
1076
    try:
 
1077
        os.rename(src, dst)
 
1078
    except OSError, (err, msg):
 
1079
        if err != errno.EEXIST:
 
1080
            raise
 
1081
 
 
1082
def action_mkdir(path, dry):
 
1083
    """Calls mkdir. Silently ignored if the directory already exists.
 
1084
    Creates all parent directories as necessary."""
 
1085
    print "mkdir -p", path
 
1086
    if dry: return
 
1087
    try:
 
1088
        os.makedirs(path)
 
1089
    except OSError, (err, msg):
 
1090
        if err != errno.EEXIST:
 
1091
            raise
 
1092
 
 
1093
def action_copytree(src, dst, dry):
 
1094
    """Copies an entire directory tree. Symlinks are seen as normal files and
 
1095
    copies of the entire file (not the link) are made. Creates all parent
 
1096
    directories as necessary.
 
1097
 
 
1098
    See shutil.copytree."""
 
1099
    # Allow copying over itself
 
1100
    if (os.path.normpath(os.path.join(os.getcwd(),src)) ==
 
1101
        os.path.normpath(os.path.join(os.getcwd(),dst))):
 
1102
        return
 
1103
    action_remove(dst, dry)
 
1104
    print "cp -r", src, dst
 
1105
    if dry: return
 
1106
    shutil.copytree(src, dst, True)
 
1107
 
 
1108
def action_linktree(src, dst, dry):
 
1109
    """Hard-links an entire directory tree. Same as copytree but the created
 
1110
    files are hard-links not actual copies. Removes the existing destination.
 
1111
    """
 
1112
    action_remove(dst, dry)
 
1113
    print "<cp with hardlinks> -r", src, dst
 
1114
    if dry: return
 
1115
    common.makeuser.linktree(src, dst)
 
1116
 
 
1117
def action_copylist(srclist, dst, dry, srcdir="."):
 
1118
    """Copies all files in a list to a new location. The files in the list
 
1119
    are read relative to the current directory, and their destinations are the
 
1120
    same paths relative to dst. Creates all parent directories as necessary.
 
1121
    srcdir is "." by default, can be overridden.
 
1122
    """
 
1123
    for srcfile in srclist:
 
1124
        dstfile = os.path.join(dst, srcfile)
 
1125
        srcfile = os.path.join(srcdir, srcfile)
 
1126
        dstdir = os.path.split(dstfile)[0]
 
1127
        if not os.path.isdir(dstdir):
 
1128
            action_mkdir(dstdir, dry)
 
1129
        print "cp -f", srcfile, dstfile
 
1130
        if not dry:
 
1131
            try:
 
1132
                shutil.copyfile(srcfile, dstfile)
 
1133
                shutil.copymode(srcfile, dstfile)
 
1134
            except shutil.Error:
 
1135
                pass
 
1136
 
 
1137
def action_copyfile(src, dst, dry):
 
1138
    """Copies one file to a new location. Creates all parent directories
 
1139
    as necessary.
 
1140
    Warn if file not found.
 
1141
    """
 
1142
    dstdir = os.path.split(dst)[0]
 
1143
    if not os.path.isdir(dstdir):
 
1144
        action_mkdir(dstdir, dry)
 
1145
    print "cp -f", src, dst
 
1146
    if not dry:
 
1147
        try:
 
1148
            shutil.copyfile(src, dst)
 
1149
            shutil.copymode(src, dst)
 
1150
        except (shutil.Error, IOError), e:
 
1151
            print "Warning: " + str(e)
 
1152
 
 
1153
def action_symlink(src, dst, dry):
 
1154
    """Creates a symlink in a given location. Creates all parent directories
 
1155
    as necessary.
 
1156
    """
 
1157
    dstdir = os.path.split(dst)[0]
 
1158
    if not os.path.isdir(dstdir):
 
1159
        action_mkdir(dstdir, dry)
 
1160
    # Delete existing file
 
1161
    if os.path.exists(dst):
 
1162
        os.remove(dst)
 
1163
    print "ln -fs", src, dst
 
1164
    if not dry:
 
1165
        os.symlink(src, dst)
 
1166
 
 
1167
def action_append(ivle_pth, ivle_www):
 
1168
    file = open(ivle_pth, 'a+')
 
1169
    file.write(ivle_www + '\n')
 
1170
    file.close()
 
1171
 
 
1172
def action_chown_setuid(file, dry):
 
1173
    """Chowns a file to root, and sets the setuid bit on the file.
 
1174
    Calling this function requires the euid to be root.
 
1175
    The actual mode of path is set to: rws--s--s
 
1176
    """
 
1177
    print "chown root:root", file
 
1178
    if not dry:
 
1179
        os.chown(file, 0, 0)
 
1180
    print "chmod a+xs", file
 
1181
    print "chmod u+rw", file
 
1182
    if not dry:
 
1183
        os.chmod(file, stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
 
1184
            | stat.S_ISUID | stat.S_IRUSR | stat.S_IWUSR)
 
1185
 
 
1186
def action_chmod_x(file, dry):
 
1187
    """Chmod 755 a file (sets permissions to rwxr-xr-x)."""
 
1188
    print "chmod 755", file
 
1189
    if not dry:
 
1190
        os.chmod(file, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR
 
1191
            | stat.S_IXGRP | stat.S_IRGRP | stat.S_IXOTH | stat.S_IROTH)
 
1192
 
 
1193
 
 
1194
def action_chmod_w(file, dry):
 
1195
    """Chmod 777 a file (sets permissions to rwxrwxrwx)."""
 
1196
    print "chmod 777", file
 
1197
    if not dry:
 
1198
        os.chmod(file, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR
 
1199
            | stat.S_IXGRP | stat.S_IWGRP | stat.S_IRGRP | stat.S_IXOTH
 
1200
            | stat.S_IWOTH | stat.S_IROTH)
 
1201
 
 
1202
def query_user(default, prompt):
 
1203
    """Prompts the user for a string, which is read from a line of stdin.
 
1204
    Exits silently if EOF is encountered. Returns the string, with spaces
 
1205
    removed from the beginning and end.
 
1206
 
 
1207
    Returns default if a 0-length line (after spaces removed) was read.
 
1208
    """
 
1209
    sys.stdout.write('%s\n    (default: "%s")\n>' % (prompt, default))
 
1210
    try:
 
1211
        val = sys.stdin.readline()
 
1212
    except KeyboardInterrupt:
 
1213
        # Ctrl+C
 
1214
        sys.stdout.write("\n")
 
1215
        sys.exit(1)
 
1216
    sys.stdout.write("\n")
 
1217
    # If EOF, exit
 
1218
    if val == '': sys.exit(1)
 
1219
    # If empty line, return default
 
1220
    val = val.strip()
 
1221
    if val == '': return default
 
1222
    return val
 
1223
 
 
1224
def filter_mutate(function, list):
 
1225
    """Like built-in filter, but mutates the given list instead of returning a
 
1226
    new one. Returns None."""
 
1227
    i = len(list)-1
 
1228
    while i >= 0:
 
1229
        # Delete elements which do not match
 
1230
        if not function(list[i]):
 
1231
            del list[i]
 
1232
        i -= 1
87
1233
 
88
1234
if __name__ == "__main__":
89
1235
    sys.exit(main())
90