23
23
# This is a command-line application, for use by the administrator.
24
# This program configures, builds and installs IVLE in three separate steps.
24
# This program is a frontend for the modules in the setup packages that
25
# configure, build and install IVLE in three separate steps.
25
26
# It is called with at least one argument, which specifies which operation to
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.
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
38
# Creates lib/conf/conf.py and trampoline/conf.h.
41
# Compiles all files and sets up a jail template in the source directory.
43
# Compiles (GCC) trampoline/trampoline.c to trampoline/trampoline.
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.
51
# setup.py install [--nojail] [--dry|n]
53
# Create target install directory ($target).
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).
73
# Import modules from the website is tricky since they're in the www
75
sys.path.append(os.path.join(os.getcwd(), 'lib'))
77
import common.makeuser
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]
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.
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',
96
# These 2 files do not exist in Ubuntu
97
#'/etc/ld.so.preload',
98
#'/etc/ld.so.nohwcap',
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',
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',
165
'/lib/libnss_dns.so.2',
166
#'/lib/libnss_mdns4.so',
171
'/etc/nsswitch.conf',
172
'/lib/libnss_files.so.2',
174
# Symlinks to make within the jail. Src mapped to dst.
176
'python%s' % PYTHON_VERSION: 'jail/usr/bin/python',
178
# Trees to copy. Src mapped to dst (these will be passed to action_copytree).
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
'/usr/share/nltk': 'jail/usr/share/nltk',
188
"""A configuration option; one of the things written to conf.py."""
189
def __init__(self, option_name, default, prompt, comment):
190
"""Creates a configuration option.
191
option_name: Name of the variable in conf.py. Also name of the
192
command-line argument to setup.py conf.
193
default: Default value for this variable.
194
prompt: (Short) string presented during the interactive prompt in
196
comment: (Long) comment string stored in conf.py. Each line of this
197
string should begin with a '#'.
199
self.option_name = option_name
200
self.default = default
202
self.comment = comment
204
# Configuration options, defaults and descriptions
206
config_options.append(ConfigOption("root_dir", "/",
207
"""Root directory where IVLE is located (in URL space):""",
209
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
211
# eg. "/" or "/ivle"."""))
212
config_options.append(ConfigOption("ivle_install_dir", "/opt/ivle",
213
'Root directory where IVLE will be installed (on the local file '
216
# In the local file system, where IVLE is actually installed.
217
# This directory should contain the "www" and "bin" directories."""))
218
config_options.append(ConfigOption("jail_base", "/home/informatics/jails",
219
"""Location of Directories
220
=======================
221
Root directory where the jails (containing user files) are stored
222
(on the local file system):""",
224
# In the local file system, where are the student/user file spaces located.
225
# The user jails are expected to be located immediately in subdirectories of
226
# this location."""))
227
config_options.append(ConfigOption("subjects_base",
228
"/home/informatics/subjects",
229
"""Root directory where the subject directories (containing worksheets
230
and other per-subject files) are stored (on the local file system):""",
232
# In the local file system, where are the per-subject file spaces located.
233
# The individual subject directories are expected to be located immediately
234
# in subdirectories of this location."""))
235
config_options.append(ConfigOption("exercises_base",
236
"/home/informatics/exercises",
237
"""Root directory where the exercise directories (containing
238
subject-independent exercise sheets) are stored (on the local file
241
# In the local file system, where are the subject-independent exercise sheet
242
# file spaces located."""))
243
config_options.append(ConfigOption("tos_path",
244
"/home/informatics/tos.html",
245
"""Location where the Terms of Service document is stored (on the local
248
# In the local file system, where is the Terms of Service document located."""))
249
config_options.append(ConfigOption("public_host", "public.localhost",
250
"""Hostname which will cause the server to go into "public mode",
251
providing login-free access to student's published work:""",
253
# The server goes into "public mode" if the browser sends a request with this
254
# host. This is for security reasons - we only serve public student files on a
255
# separate domain to the main IVLE site.
256
# Public mode does not use cookies, and serves only public content.
257
# Private mode (normal mode) requires login, and only serves files relevant to
258
# the logged-in user."""))
259
config_options.append(ConfigOption("allowed_uids", "33",
260
"""UID of the web server process which will run IVLE.
261
Only this user may execute the trampoline. May specify multiple users as
262
a comma-separated list.
265
# The User-ID of the web server process which will run IVLE, and any other
266
# users who are allowed to run the trampoline. This is stores as a string of
267
# comma-separated integers, simply because it is not used within Python, only
268
# used by the setup program to write to conf.h (see setup.py config)."""))
269
config_options.append(ConfigOption("db_host", "localhost",
270
"""PostgreSQL Database config
271
==========================
272
Hostname of the DB server:""",
274
### PostgreSQL Database config ###
275
# Database server hostname"""))
276
config_options.append(ConfigOption("db_port", "5432",
277
"""Port of the DB server:""",
279
# Database server port"""))
280
config_options.append(ConfigOption("db_dbname", "ivle",
281
"""Database name:""",
284
config_options.append(ConfigOption("db_forumdbname", "ivle_forum",
285
"""Forum Database name:""",
287
# Forum Database name"""))
288
config_options.append(ConfigOption("db_user", "postgres",
289
"""Username for DB server login:""",
291
# Database username"""))
292
config_options.append(ConfigOption("db_password", "",
293
"""Password for DB server login:
294
(Caution: This password is stored in plaintext in lib/conf/conf.py)""",
296
# Database password"""))
297
config_options.append(ConfigOption("auth_modules", "ldap_auth",
298
"""Authentication config
299
=====================
300
Comma-separated list of authentication modules. Only "ldap" is available
303
# Comma-separated list of authentication modules.
304
# These refer to importable Python modules in the www/auth directory.
305
# Modules "ldap" and "guest" are available in the source tree, but
306
# other modules may be plugged in to auth against organisation-specific
307
# auth backends."""))
308
config_options.append(ConfigOption("ldap_url", "ldaps://www.example.com",
309
"""(LDAP options are only relevant if "ldap" is included in the list of
311
URL for LDAP authentication server:""",
313
# URL for LDAP authentication server"""))
314
config_options.append(ConfigOption("ldap_format_string",
315
"uid=%s,ou=users,o=example",
316
"""Format string for LDAP auth request:
317
(Must contain a single "%s" for the user's login name)""",
319
# Format string for LDAP auth request
320
# (Must contain a single "%s" for the user's login name)"""))
321
config_options.append(ConfigOption("svn_addr", "http://svn.localhost/",
324
The base url for accessing subversion repositories:""",
326
# The base url for accessing subversion repositories."""))
327
config_options.append(ConfigOption("svn_conf", "/opt/ivle/svn/svn.conf",
328
"""The location of the subversion configuration file used by apache
329
to host the user repositories:""",
331
# The location of the subversion configuration file used by
332
# apache to host the user repositories."""))
333
config_options.append(ConfigOption("svn_repo_path", "/home/informatics/repositories",
334
"""The root directory for the subversion repositories:""",
336
# The root directory for the subversion repositories."""))
337
config_options.append(ConfigOption("svn_auth_ivle", "/opt/ivle/svn/ivle.auth",
338
"""The location of the password file used to authenticate users
339
of the subversion repository from the ivle server:""",
341
# The location of the password file used to authenticate users
342
# of the subversion repository from the ivle server."""))
343
config_options.append(ConfigOption("svn_auth_local", "/opt/ivle/svn/local.auth",
344
"""The location of the password file used to authenticate local users
345
of the subversion repository:""",
347
# The location of the password file used to authenticate local users
348
# of the subversion repository."""))
349
config_options.append(ConfigOption("usrmgt_host", "localhost",
350
"""User Management Server config
351
============================
352
The hostname where the usrmgt-server runs:""",
354
# The hostname where the usrmgt-server runs."""))
355
config_options.append(ConfigOption("usrmgt_port", "2178",
356
"""The port where the usrmgt-server runs:""",
358
# The port where the usrmgt-server runs."""))
359
config_options.append(ConfigOption("usrmgt_magic", "",
360
"""The password for the usrmgt-server:""",
362
# The password for the usrmgt-server."""))
364
# Try importing existing conf, but if we can't just set up defaults
365
# The reason for this is that these settings are used by other phases
366
# of setup besides conf, so we need to know them.
367
# Also this allows you to hit Return to accept the existing value.
369
confmodule = __import__("lib/conf/conf")
370
for opt in config_options:
372
globals()[opt.option_name] = confmodule.__dict__[opt.option_name]
374
globals()[opt.option_name] = opt.default
376
# Just set reasonable defaults
377
for opt in config_options:
378
globals()[opt.option_name] = opt.default
380
# Try importing install_list, but don't fail if we can't, because listmake can
381
# function without it.
387
# Mime types which will automatically be placed in the list by listmake.
388
# Note that listmake is not intended to be run by the final user (the system
389
# administrator who installs this), so the developers can customize the list
390
# as necessary, and include it in the distribution.
391
listmake_mimetypes = ['text/x-python', 'text/html',
392
'application/x-javascript', 'application/javascript',
393
'text/css', 'image/png', 'image/gif', 'application/xml']
395
# Main function skeleton from Guido van Rossum
396
# http://www.artima.com/weblogs/viewpost.jsp?thread=4829
30
import setup.configure
398
36
def main(argv=None):
421
# Disallow run as root unless installing
422
if (operation != 'install' and operation != 'updatejails'
423
and os.geteuid() == 0):
424
print >>sys.stderr, "I do not want to run this stage as root."
425
print >>sys.stderr, "Please run as a normal user."
427
# Call the requested operation's function
433
'listmake' : listmake,
435
'updatejails' : updatejails,
438
print >>sys.stderr, (
439
"""Invalid operation '%s'. Try python setup.py help."""
59
oper_func = call_operator(operation)
442
60
return oper_func(argv[2:])
444
# Operation functions
448
print """Usage: python setup.py operation [args]
449
Operation (and args) can be:
64
print """Usage: python setup.py operation [options]
65
Operation (and options) can be:
451
67
listmake (developer use only)
454
70
install [--nojail] [--nosubjects] [-n|--dry]
458
print """Usage: python setup.py help [operation]"""
463
if operation == 'help':
464
print """python setup.py help [operation]
465
Prints the usage message or detailed help on an operation, then exits."""
466
elif operation == 'listmake':
467
print """python setup.py listmake
468
(For developer use only)
469
Recurses through the source tree and builds a list of all files which should
470
be copied upon installation. This should be run by the developer before
471
cutting a distribution, and the listfile it generates should be included in
472
the distribution, avoiding the administrator having to run it."""
473
elif operation == 'config':
474
print """python setup.py config [args]
475
Configures IVLE with machine-specific details, most notably, various paths.
476
Either prompts the administrator for these details or accepts them as
477
command-line args. Will be interactive only if there are no arguments given.
478
Takes defaults from existing conf file if it exists.
480
To run IVLE out of the source directory (allowing development without having
481
to rebuild/install), just provide ivle_install_dir as the IVLE trunk
482
directory, and run build/install one time.
484
Creates lib/conf/conf.py and trampoline/conf.h.
487
for opt in config_options:
488
print " --" + opt.option_name
489
print """As explained in the interactive prompt or conf.py.
491
elif operation == 'build':
492
print """python -O setup.py build [--dry|-n]
493
Compiles all files and sets up a jail template in the source directory.
494
-O is recommended to cause compilation to be optimised.
496
Compiles (GCC) trampoline/trampoline.c to trampoline/trampoline.
498
Creates standard subdirs inside the jail, eg bin, opt, home, tmp.
499
Copies console/ to a location within the jail.
500
Copies OS programs and files to corresponding locations within the jail
501
(eg. python and Python libs, ld.so, etc).
502
Generates .pyc or .pyo files for all the IVLE .py files.
504
--dry | -n Print out the actions but don't do anything."""
505
elif operation == 'install':
506
print """sudo python setup.py install [--nojail] [--nosubjects][--dry|-n]
508
Create target install directory ($target).
510
Copy trampoline/trampoline to $target/bin.
511
chown and chmod the installed trampoline.
512
Copy www/ to $target.
513
Copy jail/ to jails template directory (unless --nojail specified).
514
Copy subjects/ to subjects directory (unless --nosubjects specified).
516
--nojail Do not copy the jail.
517
--nosubjects Do not copy the subjects and exercises directories.
518
--dry | -n Print out the actions but don't do anything."""
519
elif operation == 'updatejails':
520
print """sudo python setup.py updatejails [--dry|-n]
522
Copy jail/ to each subdirectory in jails directory.
524
--dry | -n Print out the actions but don't do anything."""
72
For help on a specific operation use 'help [operation]'."""
75
oper_func = call_operator(operator)
76
oper_func(['operator','--help'])
78
def call_operator(operation):
79
# Call the requested operation's function
83
'config' : setup.configure.configure,
84
'build' : setup.build.build,
85
'listmake' : setup.listmake.listmake,
86
'install' : setup.install.install,
87
#'updatejails' : None,
526
90
print >>sys.stderr, (
527
91
"""Invalid operation '%s'. Try python setup.py help."""
532
# We build two separate lists, by walking www and console
533
list_www = build_list_py_files('www')
534
list_lib = build_list_py_files('lib')
535
list_subjects = build_list_py_files('subjects', no_top_level=True)
536
list_exercises = build_list_py_files('exercises', no_top_level=True)
538
"scripts/python-console",
539
"scripts/fileservice",
540
"scripts/serveservice",
541
"scripts/usrmgt-server",
542
"scripts/diffservice",
544
# Make sure that the files generated by conf are in the list
545
# (since listmake is typically run before conf)
546
if "lib/conf/conf.py" not in list_lib:
547
list_lib.append("lib/conf/conf.py")
548
# Write these out to a file
550
# the files that will be created/overwritten
551
listfile = os.path.join(cwd, "install_list.py")
554
file = open(listfile, "w")
556
file.write("""# IVLE Configuration File
558
# Provides lists of all files to be installed by `setup.py install' from
559
# certain directories.
560
# Note that any files with the given filename plus 'c' or 'o' (that is,
561
# compiled .pyc or .pyo files) will be copied as well.
563
# List of all installable files in www directory.
565
writelist_pretty(file, list_www)
567
# List of all installable files in lib directory.
569
writelist_pretty(file, list_lib)
571
# List of all installable files in scripts directory.
573
writelist_pretty(file, list_scripts)
575
# List of all installable files in subjects directory.
576
# This is to install sample subjects and material.
578
writelist_pretty(file, list_subjects)
580
# List of all installable files in exercises directory.
581
# This is to install sample exercise material.
582
list_exercises = """)
583
writelist_pretty(file, list_exercises)
586
except IOError, (errno, strerror):
587
print "IO error(%s): %s" % (errno, strerror)
590
print "Successfully wrote install_list.py"
593
print ("You may modify the set of installable files before cutting the "
600
def build_list_py_files(dir, no_top_level=False):
601
"""Builds a list of all py files found in a directory and its
602
subdirectories. Returns this as a list of strings.
603
no_top_level=True means the file paths will not include the top-level
607
for (dirpath, dirnames, filenames) in os.walk(dir):
608
# Exclude directories beginning with a '.' (such as '.svn')
609
filter_mutate(lambda x: x[0] != '.', dirnames)
610
# All *.py files are added to the list
611
pylist += [os.path.join(dirpath, item) for item in filenames
612
if mimetypes.guess_type(item)[0] in listmake_mimetypes]
614
for i in range(0, len(pylist)):
615
_, pylist[i] = pylist[i].split(os.sep, 1)
618
def writelist_pretty(file, list):
619
"""Writes a list one element per line, to a file."""
625
file.write(' %s,\n' % repr(elem))
629
global db_port, usrmgt_port
630
# Set up some variables
633
# the files that will be created/overwritten
634
conffile = os.path.join(cwd, "lib/conf/conf.py")
635
jailconffile = os.path.join(cwd, "lib/conf/jailconf.py")
636
conf_hfile = os.path.join(cwd, "trampoline/conf.h")
637
phpBBconffile = os.path.join(cwd, "www/php/phpBB3/config.php")
639
# Get command-line arguments to avoid asking questions.
642
for opt in config_options:
643
optnames.append(opt.option_name + "=")
644
(opts, args) = getopt.gnu_getopt(args, "", optnames)
647
print >>sys.stderr, "Invalid arguments:", string.join(args, ' ')
651
# Interactive mode. Prompt the user for all the values.
653
print """This tool will create the following files:
658
prompting you for details about your configuration. The file will be
659
overwritten if it already exists. It will *not* install or deploy IVLE.
661
Please hit Ctrl+C now if you do not wish to do this.
662
""" % (conffile, jailconffile, conf_hfile, phpBBconffile)
664
# Get information from the administrator
665
# If EOF is encountered at any time during the questioning, just exit
668
for opt in config_options:
669
globals()[opt.option_name] = \
670
query_user(globals()[opt.option_name], opt.prompt)
673
# Non-interactive mode. Parse the options.
674
for opt in config_options:
675
if '--' + opt.option_name in opts:
676
globals()[opt.option_name] = opts['--' + opt.option_name]
678
# Error handling on input values
680
allowed_uids_list = map(int, allowed_uids.split(','))
682
print >>sys.stderr, (
683
"Invalid UID list (%s).\n"
684
"Must be a comma-separated list of integers." % allowed_uids)
687
db_port = int(db_port)
688
if db_port < 0 or db_port >= 65536: raise ValueError()
690
print >>sys.stderr, (
691
"Invalid DB port (%s).\n"
692
"Must be an integer between 0 and 65535." % repr(db_port))
695
usrmgt_port = int(usrmgt_port)
696
if usrmgt_port < 0 or usrmgt_port >= 65536: raise ValueError()
698
print >>sys.stderr, (
699
"Invalid user management port (%s).\n"
700
"Must be an integer between 0 and 65535." % repr(usrmgt_port))
703
# Generate the forum secret
704
forum_secret = hashlib.md5(uuid.uuid4().bytes).hexdigest()
706
# Write lib/conf/conf.py
709
conf = open(conffile, "w")
711
conf.write("""# IVLE Configuration File
713
# Miscellaneous application settings
716
for opt in config_options:
717
conf.write('%s\n%s = %s\n' % (opt.comment, opt.option_name,
718
repr(globals()[opt.option_name])))
720
# Add the forum secret to the config file (regenerated each config)
721
conf.write('forum_secret = "%s"\n' % (forum_secret))
724
except IOError, (errno, strerror):
725
print "IO error(%s): %s" % (errno, strerror)
728
print "Successfully wrote lib/conf/conf.py"
730
# Write conf/jailconf.py
733
conf = open(jailconffile, "w")
735
# In the "in-jail" version of conf, we don't need MOST of the details
736
# (it would be a security risk to have them here).
737
# So we just write root_dir, and jail_base is "/".
738
# (jail_base being "/" means "jail-relative" paths are relative to "/"
739
# when inside the jail.)
740
conf.write("""# IVLE Configuration File
742
# Miscellaneous application settings
743
# (User jail version)
746
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
748
# eg. "/" or "/ivle".
751
# In the local file system, where are the student/user file spaces located.
752
# The user jails are expected to be located immediately in subdirectories of
756
# The hostname for serving publicly accessible pages
758
""" % (repr(root_dir),repr(public_host)))
761
except IOError, (errno, strerror):
762
print "IO error(%s): %s" % (errno, strerror)
765
print "Successfully wrote lib/conf/jailconf.py"
767
# Write trampoline/conf.h
770
conf = open(conf_hfile, "w")
772
conf.write("""/* IVLE Configuration File
774
* Administrator settings required by trampoline.
775
* Note: trampoline will have to be rebuilt in order for changes to this file
779
/* In the local file system, where are the jails located.
780
* The trampoline does not allow the creation of a jail anywhere besides
781
* jail_base or a subdirectory of jail_base.
783
static const char* jail_base = "%s";
785
/* Which user IDs are allowed to run the trampoline.
786
* This list should be limited to the web server user.
787
* (Note that root is an implicit member of this list).
789
static const int allowed_uids[] = { %s };
790
""" % (repr(jail_base)[1:-1], repr(allowed_uids_list)[1:-1]))
791
# Note: The above uses PYTHON reprs, not C reprs
792
# However they should be the same with the exception of the outer
793
# characters, which are stripped off and replaced
796
except IOError, (errno, strerror):
797
print "IO error(%s): %s" % (errno, strerror)
800
print "Successfully wrote trampoline/conf.h"
802
# Write www/php/phpBB3/config.php
805
conf = open(phpBBconffile, "w")
808
if db_host == 'localhost':
809
forumdb_host = '127.0.0.1'
811
forumdb_host = db_host
814
// phpBB 3.0.x auto-generated configuration file
815
// Do not change anything in this file!
817
$dbhost = '""" + forumdb_host + """';
818
$dbport = '""" + str(db_port) + """';
819
$dbname = '""" + db_forumdbname + """';
820
$dbuser = '""" + db_user + """';
821
$dbpasswd = '""" + db_password + """';
823
$table_prefix = 'phpbb_';
825
$load_extensions = '';
826
@define('PHPBB_INSTALLED', true);
827
// @define('DEBUG', true);
828
//@define('DEBUG_EXTRA', true);
830
$forum_secret = '""" + forum_secret +"""';
834
except IOError, (errno, strerror):
835
print "IO error(%s): %s" % (errno, strerror)
838
print "Successfully wrote www/php/phpBB3/config.php"
841
print "You may modify the configuration at any time by editing"
850
# Get "dry" variable from command line
851
(opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
853
dry = '-n' in opts or '--dry' in opts
856
print "Dry run (no actions will be executed\n"
858
# Compile the trampoline
860
os.chdir('trampoline')
861
action_runprog('make', [], dry)
864
# Create the jail and its subdirectories
865
# Note: Other subdirs will be made by copying files
866
action_mkdir('jail', dry)
867
action_mkdir('jail/home', dry)
868
action_mkdir('jail/tmp', dry)
870
# Chmod the tmp directory to world writable
871
action_chmod_w('jail/tmp', dry)
873
# Copy all console and operating system files into the jail
874
action_copylist(install_list.list_scripts, 'jail/opt/ivle', dry)
875
copy_os_files_jail(dry)
876
# Chmod the python console
877
action_chmod_x('jail/opt/ivle/scripts/python-console', dry)
878
action_chmod_x('jail/opt/ivle/scripts/fileservice', dry)
879
action_chmod_x('jail/opt/ivle/scripts/serveservice', dry)
881
# Also copy the IVLE lib directory into the jail
882
# This is necessary for running certain scripts
883
action_copylist(install_list.list_lib, 'jail/opt/ivle', dry)
884
# IMPORTANT: The file jail/opt/ivle/lib/conf/conf.py contains details
885
# which could compromise security if left in the jail (such as the DB
887
# The "safe" version is in jailconf.py. Delete conf.py and replace it with
889
action_copyfile('lib/conf/jailconf.py',
890
'jail/opt/ivle/lib/conf/conf.py', dry)
892
# Compile .py files into .pyc or .pyo files
893
compileall.compile_dir('www', quiet=True)
894
compileall.compile_dir('lib', quiet=True)
895
compileall.compile_dir('scripts', quiet=True)
896
compileall.compile_dir('jail/opt/ivle/lib', quiet=True)
898
# Set up ivle.pth inside the jail
899
# Need to set /opt/ivle/lib to be on the import path
901
"jail/usr/lib/python%s/site-packages/ivle.pth" % PYTHON_VERSION
902
f = open(ivle_pth, 'w')
903
f.write('/opt/ivle/lib\n')
908
def copy_os_files_jail(dry):
909
"""Copies necessary Operating System files from their usual locations
910
into the jail/ directory of the cwd."""
911
# Currently source paths are configured for Ubuntu.
912
for filename in JAIL_FILES:
913
copy_file_to_jail(filename, dry)
914
for src, dst in JAIL_LINKS.items():
915
action_symlink(src, dst, dry)
916
for src, dst in JAIL_COPYTREES.items():
917
action_copytree(src, dst, dry)
919
def copy_file_to_jail(src, dry):
920
"""Copies a single file from an absolute location into the same location
921
within the jail. src must begin with a '/'. The jail will be located
922
in a 'jail' subdirectory of the current path."""
923
action_copyfile(src, 'jail' + src, dry)
926
# Get "dry" and "nojail" variables from command line
927
(opts, args) = getopt.gnu_getopt(args, "n",
928
['dry', 'nojail', 'nosubjects'])
930
dry = '-n' in opts or '--dry' in opts
931
nojail = '--nojail' in opts
932
nosubjects = '--nosubjects' in opts
935
print "Dry run (no actions will be executed\n"
937
if not dry and os.geteuid() != 0:
938
print >>sys.stderr, "Must be root to run install"
939
print >>sys.stderr, "(I need to chown some files)."
942
# Create the target (install) directory
943
action_mkdir(ivle_install_dir, dry)
945
# Create bin and copy the compiled files there
946
action_mkdir(os.path.join(ivle_install_dir, 'bin'), dry)
947
tramppath = os.path.join(ivle_install_dir, 'bin/trampoline')
948
action_copyfile('trampoline/trampoline', tramppath, dry)
949
# chown trampoline to root and set setuid bit
950
action_chown_setuid(tramppath, dry)
952
# Create a scripts directory to put the usrmgt-server in.
953
action_mkdir(os.path.join(ivle_install_dir, 'scripts'), dry)
954
usrmgtpath = os.path.join(ivle_install_dir, 'scripts/usrmgt-server')
955
action_copyfile('scripts/usrmgt-server', usrmgtpath, dry)
956
action_chmod_x(usrmgtpath, dry)
958
# Copy the www and lib directories using the list
959
action_copylist(install_list.list_www, ivle_install_dir, dry)
960
action_copylist(install_list.list_lib, ivle_install_dir, dry)
962
# Copy the php directory
963
forum_dir = "www/php/phpBB3"
964
forum_path = os.path.join(ivle_install_dir, forum_dir)
965
action_copytree(forum_dir, forum_path, dry)
966
print "chown -R www-data:www-data %s" % forum_path
968
os.system("chown -R www-data:www-data %s" % forum_path)
971
# Copy the local jail directory built by the build action
972
# to the jails template directory (it will be used as a template
973
# for all the students' jails).
974
action_copytree('jail', os.path.join(jail_base, 'template'), dry)
976
# Copy the subjects and exercises directories across
977
action_copylist(install_list.list_subjects, subjects_base, dry,
979
action_copylist(install_list.list_exercises, exercises_base, dry,
980
srcdir="./exercises")
982
# Append IVLE path to ivle.pth in python site packages
983
# (Unless it's already there)
984
ivle_pth = os.path.join(sys.prefix,
985
"lib/python%s/site-packages/ivle.pth" % PYTHON_VERSION)
986
ivle_www = os.path.join(ivle_install_dir, "www")
987
ivle_lib = os.path.join(ivle_install_dir, "lib")
988
write_ivle_pth = True
989
write_ivle_lib_pth = True
991
file = open(ivle_pth, 'r')
993
if line.strip() == ivle_www:
994
write_ivle_pth = False
995
elif line.strip() == ivle_lib:
996
write_ivle_lib_pth = False
998
except (IOError, OSError):
1001
action_append(ivle_pth, ivle_www)
1002
if write_ivle_lib_pth:
1003
action_append(ivle_pth, ivle_lib)
1007
def updatejails(args):
1008
# Get "dry" variable from command line
1009
(opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
1011
dry = '-n' in opts or '--dry' in opts
1014
print "Dry run (no actions will be executed\n"
1016
if not dry and os.geteuid() != 0:
1017
print >>sys.stderr, "Must be root to run install"
1018
print >>sys.stderr, "(I need to chown some files)."
1021
# Update the template jail directory in case it hasn't been installed
1023
action_copytree('jail', os.path.join(jail_base, 'template'), dry)
1025
# Re-link all the files in all students jails.
1026
for dir in os.listdir(jail_base):
1027
if dir == 'template': continue
1028
# First back up the student's home directory
1029
temp_home = os.tmpnam()
1030
action_rename(os.path.join(jail_base, dir, 'home'), temp_home, dry)
1031
# Delete the student's jail and relink the jail files
1032
action_linktree(os.path.join(jail_base, 'template'),
1033
os.path.join(jail_base, dir), dry)
1034
# Restore the student's home directory
1035
action_rename(temp_home, os.path.join(jail_base, dir, 'home'), dry)
1036
# Set up the user's home directory just in case they don't have a
1037
# directory for this yet
1038
action_mkdir(os.path.join(jail_base, dir, 'home', dir), dry)
1042
# The actions call Python os functions but print actions and handle dryness.
1043
# May still throw os exceptions if errors occur.
1046
"""Represents an error when running a program (nonzero return)."""
1047
def __init__(self, prog, retcode):
1049
self.retcode = retcode
1051
return str(self.prog) + " returned " + repr(self.retcode)
1053
def action_runprog(prog, args, dry):
1054
"""Runs a unix program. Searches in $PATH. Synchronous (waits for the
1055
program to return). Runs in the current environment. First prints the
1056
action as a "bash" line.
1058
Throws a RunError with a retcode of the return value of the program,
1059
if the program did not return 0.
1061
prog: String. Name of the program. (No path required, if in $PATH).
1062
args: [String]. Arguments to the program.
1063
dry: Bool. If True, prints but does not execute.
1065
print prog, string.join(args, ' ')
1067
ret = os.spawnvp(os.P_WAIT, prog, args)
1069
raise RunError(prog, ret)
1071
def action_remove(path, dry):
1072
"""Calls rmtree, deleting the target file if it exists."""
1076
shutil.rmtree(path, True)
1077
except OSError, (err, msg):
1078
if err != errno.EEXIST:
1080
# Otherwise, didn't exist, so we don't care
1082
def action_rename(src, dst, dry):
1083
"""Calls rename. Deletes the target if it already exists."""
1084
action_remove(dst, dry)
1085
print "mv ", src, dst
1089
except OSError, (err, msg):
1090
if err != errno.EEXIST:
1093
def action_mkdir(path, dry):
1094
"""Calls mkdir. Silently ignored if the directory already exists.
1095
Creates all parent directories as necessary."""
1096
print "mkdir -p", path
1100
except OSError, (err, msg):
1101
if err != errno.EEXIST:
1104
def action_copytree(src, dst, dry):
1105
"""Copies an entire directory tree. Symlinks are seen as normal files and
1106
copies of the entire file (not the link) are made. Creates all parent
1107
directories as necessary.
1109
See shutil.copytree."""
1110
# Allow copying over itself
1111
if (os.path.normpath(os.path.join(os.getcwd(),src)) ==
1112
os.path.normpath(os.path.join(os.getcwd(),dst))):
1114
action_remove(dst, dry)
1115
print "cp -r", src, dst
1117
shutil.copytree(src, dst, True)
1119
def action_linktree(src, dst, dry):
1120
"""Hard-links an entire directory tree. Same as copytree but the created
1121
files are hard-links not actual copies. Removes the existing destination.
1123
action_remove(dst, dry)
1124
print "<cp with hardlinks> -r", src, dst
1126
common.makeuser.linktree(src, dst)
1128
def action_copylist(srclist, dst, dry, srcdir="."):
1129
"""Copies all files in a list to a new location. The files in the list
1130
are read relative to the current directory, and their destinations are the
1131
same paths relative to dst. Creates all parent directories as necessary.
1132
srcdir is "." by default, can be overridden.
1134
for srcfile in srclist:
1135
dstfile = os.path.join(dst, srcfile)
1136
srcfile = os.path.join(srcdir, srcfile)
1137
dstdir = os.path.split(dstfile)[0]
1138
if not os.path.isdir(dstdir):
1139
action_mkdir(dstdir, dry)
1140
print "cp -f", srcfile, dstfile
1143
shutil.copyfile(srcfile, dstfile)
1144
shutil.copymode(srcfile, dstfile)
1145
except shutil.Error:
1148
def action_copyfile(src, dst, dry):
1149
"""Copies one file to a new location. Creates all parent directories
1151
Warn if file not found.
1153
dstdir = os.path.split(dst)[0]
1154
if not os.path.isdir(dstdir):
1155
action_mkdir(dstdir, dry)
1156
print "cp -f", src, dst
1159
shutil.copyfile(src, dst)
1160
shutil.copymode(src, dst)
1161
except (shutil.Error, IOError), e:
1162
print "Warning: " + str(e)
1164
def action_symlink(src, dst, dry):
1165
"""Creates a symlink in a given location. Creates all parent directories
1168
dstdir = os.path.split(dst)[0]
1169
if not os.path.isdir(dstdir):
1170
action_mkdir(dstdir, dry)
1171
# Delete existing file
1172
if os.path.exists(dst):
1174
print "ln -fs", src, dst
1176
os.symlink(src, dst)
1178
def action_append(ivle_pth, ivle_www):
1179
file = open(ivle_pth, 'a+')
1180
file.write(ivle_www + '\n')
1183
def action_chown_setuid(file, dry):
1184
"""Chowns a file to root, and sets the setuid bit on the file.
1185
Calling this function requires the euid to be root.
1186
The actual mode of path is set to: rws--s--s
1188
print "chown root:root", file
1190
os.chown(file, 0, 0)
1191
print "chmod a+xs", file
1192
print "chmod u+rw", file
1194
os.chmod(file, stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
1195
| stat.S_ISUID | stat.S_IRUSR | stat.S_IWUSR)
1197
def action_chmod_x(file, dry):
1198
"""Chmod 755 a file (sets permissions to rwxr-xr-x)."""
1199
print "chmod 755", file
1201
os.chmod(file, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR
1202
| stat.S_IXGRP | stat.S_IRGRP | stat.S_IXOTH | stat.S_IROTH)
1205
def action_chmod_w(file, dry):
1206
"""Chmod 777 a file (sets permissions to rwxrwxrwx)."""
1207
print "chmod 777", file
1209
os.chmod(file, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR
1210
| stat.S_IXGRP | stat.S_IWGRP | stat.S_IRGRP | stat.S_IXOTH
1211
| stat.S_IWOTH | stat.S_IROTH)
1213
def query_user(default, prompt):
1214
"""Prompts the user for a string, which is read from a line of stdin.
1215
Exits silently if EOF is encountered. Returns the string, with spaces
1216
removed from the beginning and end.
1218
Returns default if a 0-length line (after spaces removed) was read.
1220
sys.stdout.write('%s\n (default: "%s")\n>' % (prompt, default))
1222
val = sys.stdin.readline()
1223
except KeyboardInterrupt:
1225
sys.stdout.write("\n")
1227
sys.stdout.write("\n")
1229
if val == '': sys.exit(1)
1230
# If empty line, return default
1232
if val == '': return default
1235
def filter_mutate(function, list):
1236
"""Like built-in filter, but mutates the given list instead of returning a
1237
new one. Returns None."""
1240
# Delete elements which do not match
1241
if not function(list[i]):
1245
96
if __name__ == "__main__":