2
# Copyright (C) 2007-2008 The University of Melbourne
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.
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.
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
18
# Module: File Service / Action
22
# Handles actions requested by the client as part of the 2-stage process of
23
# fileservice (the second part being the return listing).
27
# The most important argument is "action". This determines which action is
28
# taken. Note that action, and all other arguments, are ignored unless the
29
# request is a POST request. The other arguments depend upon the action.
30
# Note that paths are often specified as arguments. Paths that begin with a
31
# slash are taken relative to the user's home directory (the top-level
32
# directory seen when fileservice has no arguments or path). Paths without a
33
# slash are taken relative to the specified path.
35
# action=remove: Delete a file(s) or directory(s) (recursively).
36
# path: The path to the file or directory to delete. Can be specified
39
# action=move: Move or rename a file or directory.
40
# from: The path to the file or directory to be renamed.
41
# to: The path of the target filename. Error if the file already
44
# action=putfile: Upload a file to the student workspace.
45
# path: The path to the file to be written. Error if the target
46
# file is a directory.
47
# data: Bytes to be written to the file verbatim. May either be
48
# a string variable or a file upload.
49
# overwrite: Optional. If supplied, the file will be overwritten.
50
# Otherwise, error if path already exists.
52
# action=putfiles: Upload multiple files to the student workspace, and
53
# optionally accept zip files which will be unpacked.
54
# path: The path to the DIRECTORY to place files in. Must not be a
56
# data: A file upload (may not be a simple string). The filename
57
# will be used to determine the target filename within
59
# unpack: Optional. If supplied, if any data is a valid ZIP file,
60
# will create a directory instead and unpack the ZIP file
63
# action=mkdir: Create a directory. The parent dir must exist.
64
# path: The path to a file which does not exist, but whose parent
65
# does. The dir will be made with this name.
67
# The differences between putfile and putfiles are:
68
# * putfile can only accept a single file, and can't unpack zipfiles.
69
# * putfile can accept string data, doesn't have to be a file upload.
70
# * putfile ignores the upload filename, the entire filename is specified on
71
# path. putfiles calls files after the name on the user's machine.
73
# action=paste: Copy or move the files to a specified dir.
74
# src: The path to the DIRECTORY to get the files from (relative).
75
# dst: The path to the DIRECTORY to paste the files to. Must not
77
# mode: 'copy' or 'move'
78
# file: File to be copied or moved, relative to src, to a destination
79
# relative to dst. Can be specified multiple times.
82
# action=svnadd: Add an existing file(s) to version control.
83
# path: The path to the file to be added. Can be specified multiple
86
# action=svnrevert: Revert a file(s) to its state as of the current revision
88
# path: The path to the file to be reverted. Can be specified multiple
91
# action=svnupdate: Bring a file up to date with the head revision.
92
# path: The path to the file to be updated. Only one file may be
94
# revision: The revision number to update to. If not provided this
97
# action=svncommit: Commit a file(s) or directory(s) to the repository.
98
# path: The path to the file or directory to be committed. Can be
99
# specified multiple times. Directories are committed
101
# logmsg: Text of the log message. Optional. There is a default log
102
# message if unspecified.
103
# action=svncheckout: Checkout a file/directory from the repository.
104
# path: The [repository] path to the file or directory to be
107
# action=svnrepomkdir: Create a directory in a repository (not WC).
108
# path: The path to the directory to be created (under the IVLE
110
# logmsg: Text of the log message.
112
# action=svnrepostat: Check if a path exists in a repository (not WC).
113
# path: The path to the directory to be checked (under the IVLE
116
# action=svncleanup: Recursively clean up the working copy, removing locks,
117
# resuming unfinished operations, etc.
118
# path: The path to the directory to be cleaned
120
# TODO: Implement the following actions:
122
# TODO: Implement ZIP unpacking in putfiles (done?).
123
# TODO: svnupdate needs a digest to tell the user the files that were updated.
124
# This can be implemented by some message passing between action and
125
# listing, and having the digest included in the listing. (Problem if
126
# the listing is not a directory, but we could make it an error to do an
127
# update if the path is not a directory).
136
from ivle import (util, studpath, zip)
137
from ivle.fileservice_lib.exceptions import WillNotOverwrite
141
# Make a Subversion client object (which will log in with this user's
142
# credentials, upon request)
143
svnclient = ivle.svn.create_auth_svn_client(username=ivle.conf.login,
144
password=ivle.conf.svn_pass)
145
svnclient.exception_style = 0 # Simple (string) exceptions
147
DEFAULT_LOGMESSAGE = "No log message supplied."
150
# application/json is the "best" content type but is not good for
151
# debugging because Firefox just tries to download it
152
mime_dirlisting = "text/html"
153
#mime_dirlisting = "application/json"
155
class ActionError(Exception):
156
"""Represents an error processing an action. This can be
157
raised by any of the action functions, and will be caught
158
by the top-level handler, put into the HTTP response field,
161
Important Security Consideration: The message passed to this
162
exception will be relayed to the client.
166
def handle_action(req, action, fields):
167
"""Perform the "action" part of the response.
168
This function should only be called if the response is a POST.
169
This performs the action's side-effect on the server. If unsuccessful,
170
writes the X-IVLE-Action-Error header to the request object. Otherwise,
171
does not touch the request object. Does NOT write any bytes in response.
173
May throw an ActionError. The caller should put this string into the
174
X-IVLE-Action-Error header, and then continue normally.
176
action: String, the action requested. Not sanitised.
177
fields: FieldStorage object containing all arguments passed.
179
global actions_table # Table of function objects
181
action = actions_table[action]
183
# Default, just send an error but then continue
184
raise ActionError("Unknown action")
185
return action(req, fields)
187
def actionpath_to_urlpath(req, path):
188
"""Determines the URL path (relative to the student home) upon which the
189
action is intended to act. See actionpath_to_local.
193
elif len(path) > 0 and path[0] == os.sep:
194
# Relative to student home
197
# Relative to req.path
198
return os.path.join(req.path, path)
200
def actionpath_to_local(req, path):
201
"""Determines the local path upon which an action is intended to act.
202
Note that fileservice actions accept two paths: the request path,
203
and the "path" argument given to the action.
204
According to the rules, if the "path" argument begins with a '/' it is
205
relative to the user's home; if it does not, it is relative to the
208
This resolves the path, given the request and path argument.
210
May raise an ActionError("Invalid path"). The caller is expected to
211
let this fall through to the top-level handler, where it will be
212
put into the HTTP response field. Never returns None.
216
r = studpath.to_home_path(actionpath_to_urlpath(req, path))
218
raise ActionError("Invalid path")
221
def movefile(req, frompath, topath, copy=False):
222
"""Performs a file move, resolving filenames, checking for any errors,
223
and throwing ActionErrors if necessary. Can also be used to do a copy
226
frompath and topath are straight paths from the client. Will be checked.
228
# TODO: Do an SVN mv if the file is versioned.
229
# TODO: Disallow tampering with student's home directory
230
if frompath is None or topath is None:
231
raise ActionError("Required field missing")
232
frompath = actionpath_to_local(req, frompath)
233
topath = actionpath_to_local(req, topath)
234
if not os.path.exists(frompath):
235
raise ActionError("The source file does not exist")
236
if os.path.exists(topath):
237
if frompath == topath:
238
raise ActionError("Source and destination are the same")
239
raise ActionError("A file already exists with that name")
243
if os.path.isdir(frompath):
244
shutil.copytree(frompath, topath)
246
shutil.copy2(frompath, topath)
248
shutil.move(frompath, topath)
250
raise ActionError("Could not move the file specified")
252
raise ActionError("Could not move the file specified")
254
def svn_movefile(req, frompath, topath, copy=False):
255
"""Performs an svn move, resolving filenames, checking for any errors,
256
and throwing ActionErrors if necessary. Can also be used to do a copy
259
frompath and topath are straight paths from the client. Will be checked.
261
if frompath is None or topath is None:
262
raise ActionError("Required field missing")
263
frompath = actionpath_to_local(req, frompath)
264
topath = actionpath_to_local(req, topath)
265
if not os.path.exists(frompath):
266
raise ActionError("The source file does not exist")
267
if os.path.exists(topath):
268
if frompath == topath:
269
raise ActionError("Source and destination are the same")
270
raise ActionError("A file already exists with that name")
274
svnclient.copy(frompath, topath)
276
svnclient.move(frompath, topath)
278
raise ActionError("Could not move the file specified")
279
except pysvn.ClientError:
280
raise ActionError("Could not move the file specified")
285
def action_delete(req, fields):
286
# TODO: Disallow removal of student's home directory
287
"""Removes a list of files or directories.
289
Reads fields: 'path' (multiple)
291
paths = fields.getlist('path')
294
path = actionpath_to_local(req, path)
296
if os.path.isdir(path):
306
raise ActionError("Could not delete the file specified")
309
"Could not delete one or more of the files specified")
311
def action_move(req, fields):
312
# TODO: Do an SVN mv if the file is versioned.
313
# TODO: Disallow tampering with student's home directory
314
"""Removes a list of files or directories.
316
Reads fields: 'from', 'to'
318
frompath = fields.getfirst('from')
319
topath = fields.getfirst('to')
320
svn = fields.getfirst('svn')
322
svn_movefile(req, frompath, topath)
324
movefile(req, frompath, topath)
326
def action_mkdir(req, fields):
327
"""Creates a directory with the given path.
330
path = fields.getfirst('path')
332
raise ActionError("Required field missing")
333
path = actionpath_to_local(req, path)
335
if os.path.exists(path):
336
raise ActionError("A file already exists with that name")
338
# Create the directory
342
raise ActionError("Could not create directory")
344
def action_putfile(req, fields):
345
"""Writes data to a file, overwriting it if it exists and creating it if
348
Reads fields: 'path', 'data' (file upload), 'overwrite'
350
# TODO: Read field "unpack".
351
# Important: Data is "None" if the file submitted is empty.
352
path = fields.getfirst('path')
353
data = fields.getfirst('data')
355
raise ActionError("Required field missing")
357
# Workaround - field reader treats "" as None, so this is the only
358
# way to allow blank file uploads
360
path = actionpath_to_local(req, path)
363
data = cStringIO.StringIO(data)
365
overwrite = fields.getfirst('overwrite')
366
if overwrite is None:
372
# Overwrite files; but can't if it's a directory
373
if os.path.isdir(path):
374
raise ActionError("A directory already exists "
377
if os.path.exists(path):
378
raise ActionError("A file already exists with that name")
380
# Copy the contents of file object 'data' to the path 'path'
382
dest = open(path, 'wb')
384
shutil.copyfileobj(data, dest)
385
except (IOError, OSError), e:
386
raise ActionError("Could not write to target file: %s" % e.strerror)
388
def action_putfiles(req, fields):
389
"""Writes data to one or more files in a directory, overwriting them if
392
Reads fields: 'path', 'data' (file upload, multiple), 'unpack'
394
# Important: Data is "None" if the file submitted is empty.
395
path = fields.getfirst('path')
396
data = fields['data']
397
if type(data) != type([]):
399
unpack = fields.getfirst('unpack')
405
raise ActionError("Required field missing")
406
path = actionpath_to_urlpath(req, path)
410
# Each of the uploaded files
411
filepath = os.path.join(path, datum.filename)
412
filepath_local = studpath.to_home_path(filepath)
413
if os.path.isdir(filepath_local):
414
raise ActionError("A directory already exists "
417
if os.path.exists(filepath_local):
418
raise ActionError("A file already exists with that name")
419
filedata = datum.file
421
if unpack and datum.filename.lower().endswith(".zip"):
422
# A zip file - unpack it instead of just copying
423
# TODO: Use the magic number instead of file extension
424
# Note: Just unzip into the current directory (ignore the
427
# First get the entire path (within jail)
428
abspath = studpath.to_home_path(path)
429
abspath = os.path.join(os.sep, abspath)
430
zip.unzip(abspath, filedata)
431
except (OSError, IOError):
433
except WillNotOverwrite, e:
434
raise ActionError("File '" + e.filename + "' already exists.")
437
filepath_local = studpath.to_home_path(filepath)
438
if filepath_local is None:
439
raise ActionError("Invalid path")
441
# Copy the contents of file object 'data' to the path 'path'
443
dest = open(filepath_local, 'wb')
445
shutil.copyfileobj(filedata, dest)
446
except (OSError, IOError):
447
# TODO: Be more descriptive.
452
raise ActionError("Could not write to target file")
455
"Could not write to one or more of the target files")
457
def action_paste(req, fields):
458
"""Performs the copy or move action with the files specified.
459
Copies/moves the files to the specified directory.
461
Reads fields: 'src', 'dst', 'mode', 'file' (multiple).
462
src: Base path that all the files are relative to (source).
463
dst: Destination path to paste into.
464
mode: 'copy' or 'move'.
465
file: (Multiple) Files relative to base, which will be copied
466
or moved to new locations relative to path.
470
dst = fields.getfirst('dst')
471
src = fields.getfirst('src')
472
mode = fields.getfirst('mode')
473
files = fields.getlist('file')
474
if dst is None or src is None or mode is None:
475
raise ActionError("Required field missing")
477
dst_local = actionpath_to_local(req, dst)
478
if not os.path.isdir(dst_local):
479
raise ActionError("dst is not a directory")
483
# The source must not be interpreted as relative to req.path
484
# Add a slash (relative to top-level)
487
frompath = os.path.join(src, file)
488
# The destination is found by taking just the basename of the file
489
topath = os.path.join(dst, os.path.basename(file))
492
movefile(req, frompath, topath, True)
494
movefile(req, frompath, topath, False)
495
elif mode == "svncopy":
496
svn_movefile(req, frompath, topath, True)
497
elif mode == "svnmove":
498
svn_movefile(req, frompath, topath, False)
500
raise ActionError("Invalid mode (must be '(svn)copy' or '(svn)move')")
501
except ActionError, message:
502
# Store the error for later; we want to copy as many as possible
506
# Multiple errors; generic message
507
errormsg = "One or more files could not be pasted"
508
# Add this file to errorfiles; it will be put back on the
509
# clipboard for possible future pasting.
510
errorfiles.append(file)
511
if errormsg is not None:
512
raise ActionError(errormsg)
514
# XXX errorfiles contains a list of files that couldn't be pasted.
515
# we currently do nothing with this.
517
def action_publish(req,fields):
518
"""Marks the folder as published by adding a '.published' file to the
519
directory and ensuring that the parent directory permissions are correct
523
paths = fields.getlist('path')
524
user = util.split_path(req.path)[0]
525
homedir = "/home/%s" % user
527
paths = map(lambda path: actionpath_to_local(req, path), paths)
529
paths = [studpath.to_home_path(req.path)]
531
# Set all the dirs in home dir world browsable (o+r,o+x)
532
#FIXME: Should really only do those in the direct path not all of the
533
# folders in a students home directory
534
for root,dirs,files in os.walk(homedir):
535
os.chmod(root, os.stat(root).st_mode|0005)
539
if os.path.isdir(path):
540
pubfile = open(os.path.join(path,'.published'),'w')
541
pubfile.write("This directory is published\n")
544
raise ActionError("Can only publish directories")
546
raise ActionError("Directory could not be published")
548
def action_unpublish(req,fields):
549
"""Marks the folder as unpublished by removing a '.published' file in the
550
directory (if it exits). It does not change the permissions of the parent
555
paths = fields.getlist('path')
557
paths = map(lambda path: actionpath_to_local(req, path), paths)
559
paths = [studpath.to_home_path(req.path)]
563
if os.path.isdir(path):
564
pubfile = os.path.join(path,'.published')
565
if os.path.isfile(pubfile):
568
raise ActionError("Can only unpublish directories")
570
raise ActionError("Directory could not be unpublished")
573
def action_svnadd(req, fields):
574
"""Performs a "svn add" to each file specified.
576
Reads fields: 'path' (multiple)
578
paths = fields.getlist('path')
579
paths = map(lambda path: actionpath_to_local(req, path).decode('utf-8'),
583
svnclient.add(paths, recurse=True, force=True)
584
except pysvn.ClientError, e:
585
raise ActionError(str(e))
587
def action_svnremove(req, fields):
588
"""Performs a "svn remove" on each file specified.
590
Reads fields: 'path' (multiple)
592
paths = fields.getlist('path')
593
paths = map(lambda path: actionpath_to_local(req, path).decode('utf-8'),
597
svnclient.remove(paths, force=True)
598
except pysvn.ClientError, e:
599
raise ActionError(str(e))
601
def action_svnupdate(req, fields):
602
"""Performs a "svn update" to each file specified.
604
Reads fields: 'path' and 'revision'
606
path = fields.getfirst('path')
607
revision = fields.getfirst('revision')
609
raise ActionError("Required field missing")
611
revision = pysvn.Revision( pysvn.opt_revision_kind.head )
614
revision = pysvn.Revision(pysvn.opt_revision_kind.number,
616
except ValueError, e:
617
raise ActionError("Bad revision number: '%s'"%revision,)
618
path = actionpath_to_local(req, path).decode('utf-8')
621
svnclient.update(path, recurse=True, revision=revision)
622
except pysvn.ClientError, e:
623
raise ActionError(str(e))
625
def action_svnresolved(req, fields):
626
"""Performs a "svn resolved" to each file specified.
630
path = fields.getfirst('path')
632
raise ActionError("Required field missing")
633
path = actionpath_to_local(req, path).decode('utf-8')
636
svnclient.resolved(path, recurse=True)
637
except pysvn.ClientError, e:
638
raise ActionError(str(e))
640
def action_svnrevert(req, fields):
641
"""Performs a "svn revert" to each file specified.
643
Reads fields: 'path' (multiple)
645
paths = fields.getlist('path')
646
paths = map(lambda path: actionpath_to_local(req, path).decode('utf-8'),
650
svnclient.revert(paths, recurse=True)
651
except pysvn.ClientError, e:
652
raise ActionError(str(e))
654
def action_svncommit(req, fields):
655
"""Performs a "svn commit" to each file specified.
657
Reads fields: 'path' (multiple), 'logmsg' (optional)
659
paths = fields.getlist('path')
661
paths = map(lambda path:actionpath_to_local(req,path).decode('utf-8'),
664
paths = [studpath.to_home_path(req.path).decode('utf-8')]
665
logmsg = str(fields.getfirst('logmsg',
666
DEFAULT_LOGMESSAGE)).decode('utf-8')
667
if logmsg == '': logmsg = DEFAULT_LOGMESSAGE
670
svnclient.checkin(paths, logmsg, recurse=True)
671
except pysvn.ClientError, e:
672
raise ActionError(str(e))
674
def action_svncheckout(req, fields):
675
"""Performs a "svn checkout" of the first path into the second path.
677
Reads fields: 'path' (multiple)
679
paths = fields.getlist('path')
681
raise ActionError("usage: svncheckout url local-path")
682
url = ivle.conf.svn_addr + "/" + urllib.quote(paths[0])
683
local_path = actionpath_to_local(req, str(paths[1]))
684
url = url.decode('utf-8')
685
local_path = local_path.decode('utf-8')
687
svnclient.checkout(url, local_path, recurse=True)
688
except pysvn.ClientError, e:
689
raise ActionError(str(e))
691
def action_svnrepomkdir(req, fields):
692
"""Performs a "svn mkdir" on a path under the IVLE SVN root.
696
path = fields.getfirst('path')
697
logmsg = fields.getfirst('logmsg')
698
url = (ivle.conf.svn_addr + "/" + urllib.quote(path)).decode('utf-8')
700
svnclient.mkdir(url, log_message=logmsg)
701
except pysvn.ClientError, e:
702
raise ActionError(str(e))
704
def action_svnrepostat(req, fields):
705
"""Discovers whether a path exists in a repo under the IVLE SVN root.
707
If it does exist, returns a dict containing its metadata.
711
path = fields.getfirst('path')
712
url = (ivle.conf.svn_addr + "/" + urllib.quote(path)).decode('utf-8')
713
svnclient.exception_style = 1
716
info = svnclient.info2(url,
717
revision=pysvn.Revision(pysvn.opt_revision_kind.head))[0][1]
718
return {'svnrevision': info['rev'].number
720
info['rev'].kind == pysvn.opt_revision_kind.number
722
except pysvn.ClientError, e:
723
# Error code 170000 means ENOENT in this revision.
724
if e[1][0][1] == 170000:
726
raise ActionError('The specified repository path does not exist')
728
raise ActionError(str(e[0]))
731
def action_svncleanup(req, fields):
732
"""Recursively clean up the working copy, removing locks, resuming
733
unfinished operations, etc.
734
path: The path to be cleaned"""
736
path = fields.getfirst('path')
738
raise ActionError("Required field missing")
739
path = actionpath_to_local(req, path).decode('utf-8')
742
svnclient.cleanup(path)
743
except pysvn.ClientError, e:
744
raise ActionError(str(e))
747
# Table of all action functions #
748
# Each function has the interface f(req, fields).
751
"delete" : action_delete,
752
"move" : action_move,
753
"mkdir" : action_mkdir,
754
"putfile" : action_putfile,
755
"putfiles" : action_putfiles,
756
"paste" : action_paste,
757
"publish" : action_publish,
758
"unpublish" : action_unpublish,
760
"svnadd" : action_svnadd,
761
"svnremove" : action_svnremove,
762
"svnupdate" : action_svnupdate,
763
"svnresolved" : action_svnresolved,
764
"svnrevert" : action_svnrevert,
765
"svncommit" : action_svncommit,
766
"svncheckout" : action_svncheckout,
767
"svnrepomkdir" : action_svnrepomkdir,
768
"svnrepostat" : action_svnrepostat,
769
"svncleanup" : action_svncleanup,