3 from twisted.application import service, strports, internet
4 from twisted.web import static, resource, server, html, http
5 from twisted.python import log
6 from twisted.internet import defer, address
7 from twisted.internet.interfaces import IConsumer
8 from nevow import inevow, rend, loaders, appserver, url, tags as T
9 from nevow.static import File as nevow_File # TODO: merge with static.File?
10 from allmydata.util import fileutil, idlib
12 from allmydata.interfaces import IDownloadTarget, IDirectoryNode, IFileNode, \
14 import allmydata # to display import path
15 from allmydata import download
16 from allmydata.upload import FileHandle, FileName
17 from allmydata import provisioning
18 from allmydata import get_package_versions_string
19 from zope.interface import implements, Interface
21 from formless import webform
23 from nevow.util import resource_filename
26 return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
28 class IClient(Interface):
30 class ILocalAccess(Interface):
31 def local_access_is_allowed():
32 """Return True if t=upload&localdir= is allowed, giving anyone who
33 can talk to the webserver control over the local (disk) filesystem."""
35 def boolean_of_arg(arg):
36 assert arg.lower() in ("true", "t", "1", "false", "f", "0")
37 return arg.lower() in ("true", "t", "1")
39 def get_arg(req, argname, default=None, multiple=False):
40 """Extract an argument from either the query args (req.args) or the form
41 body fields (req.fields). If multiple=False, this returns a single value
42 (or the default, which defaults to None), and the query args take
43 precedence. If multiple=True, this returns a tuple of arguments (possibly
44 empty), starting with all those in the query args.
47 if argname in req.args:
48 results.extend(req.args[argname])
49 if req.fields and argname in req.fields:
50 results.append(req.fields[argname].value)
57 # we must override twisted.web.http.Request.requestReceived with a version
58 # that doesn't use cgi.parse_multipart() . Since we actually use Nevow, we
59 # override the nevow-specific subclass, nevow.appserver.NevowRequest . This
60 # is an exact copy of twisted.web.http.Request (from SVN HEAD on 10-Aug-2007)
61 # that modifies the way form arguments are parsed. Note that this sort of
62 # surgery may induce a dependency upon a particular version of twisted.web
64 parse_qs = http.parse_qs
65 class MyRequest(appserver.NevowRequest):
67 def requestReceived(self, command, path, version):
68 """Called by channel when all data has been received.
70 This method is not intended for users.
72 self.content.seek(0,0)
76 self.method, self.uri = command, path
77 self.clientproto = version
78 x = self.uri.split('?', 1)
83 self.path, argstring = x
84 self.args = parse_qs(argstring, 1)
86 # cache the client and server information, we'll need this later to be
87 # serialized and sent with the request so CGIs will work remotely
88 self.client = self.channel.transport.getPeer()
89 self.host = self.channel.transport.getHost()
91 # Argument processing.
93 ## The original twisted.web.http.Request.requestReceived code parsed the
94 ## content and added the form fields it found there to self.args . It
95 ## did this with cgi.parse_multipart, which holds the arguments in RAM
96 ## and is thus unsuitable for large file uploads. The Nevow subclass
97 ## (nevow.appserver.NevowRequest) uses cgi.FieldStorage instead (putting
98 ## the results in self.fields), which is much more memory-efficient.
99 ## Since we know we're using Nevow, we can anticipate these arguments
100 ## appearing in self.fields instead of self.args, and thus skip the
101 ## parse-content-into-self.args step.
104 ## ctype = self.getHeader('content-type')
105 ## if self.method == "POST" and ctype:
106 ## mfd = 'multipart/form-data'
107 ## key, pdict = cgi.parse_header(ctype)
108 ## if key == 'application/x-www-form-urlencoded':
109 ## args.update(parse_qs(self.content.read(), 1))
112 ## args.update(cgi.parse_multipart(self.content, pdict))
113 ## except KeyError, e:
114 ## if e.args[0] == 'content-disposition':
115 ## # Parse_multipart can't cope with missing
116 ## # content-dispostion headers in multipart/form-data
117 ## # parts, so we catch the exception and tell the client
118 ## # it was a bad request.
119 ## self.channel.transport.write(
120 ## "HTTP/1.1 400 Bad Request\r\n\r\n")
121 ## self.channel.transport.loseConnection()
127 class Directory(rend.Page):
129 docFactory = getxmlfile("directory.xhtml")
131 def __init__(self, rootname, dirnode, dirpath):
132 self._rootname = rootname
133 self._dirnode = dirnode
134 self._dirpath = dirpath
136 def dirpath_as_string(self):
137 return "/" + "/".join(self._dirpath)
139 def render_title(self, ctx, data):
140 return ctx.tag["Directory '%s':" % self.dirpath_as_string()]
142 def render_header(self, ctx, data):
143 parent_directories = ("<%s>" % self._rootname,) + self._dirpath
144 num_dirs = len(parent_directories)
146 header = ["Directory '"]
147 for i,d in enumerate(parent_directories):
148 upness = num_dirs - i - 1
150 link = "/".join( ("..",) * upness )
153 header.append(T.a(href=link)[d])
158 if self._dirnode.is_readonly():
159 header.append(" (readonly)")
161 return ctx.tag[header]
163 def render_welcome(self, ctx, data):
164 depth = len(self._dirpath) + 2
165 link = "/".join([".."] * depth)
166 return T.div[T.a(href=link)["Return to Welcome page"]]
168 def data_children(self, ctx, data):
169 d = self._dirnode.list()
170 d.addCallback(lambda dict: sorted(dict.items()))
173 def render_row(self, ctx, data):
174 name, (target, metadata) = data
176 if self._dirnode.is_readonly():
180 # this creates a button which will cause our child__delete method
181 # to be invoked, which deletes the file and then redirects the
182 # browser back to this directory
183 delete = T.form(action=url.here, method="post")[
184 T.input(type='hidden', name='t', value='delete'),
185 T.input(type='hidden', name='name', value=name),
186 T.input(type='hidden', name='when_done', value=url.here),
187 T.input(type='submit', value='del', name="del"),
190 rename = T.form(action=url.here, method="get")[
191 T.input(type='hidden', name='t', value='rename-form'),
192 T.input(type='hidden', name='name', value=name),
193 T.input(type='hidden', name='when_done', value=url.here),
194 T.input(type='submit', value='rename', name="rename"),
197 ctx.fillSlots("delete", delete)
198 ctx.fillSlots("rename", rename)
199 check = T.form(action=url.here, method="post")[
200 T.input(type='hidden', name='t', value='check'),
201 T.input(type='hidden', name='name', value=name),
202 T.input(type='hidden', name='when_done', value=url.here),
203 T.input(type='submit', value='check', name="check"),
205 ctx.fillSlots("overwrite", self.build_overwrite(ctx, (name, target)))
206 ctx.fillSlots("check", check)
208 # build the base of the uri_link link url
209 uri_link = "/uri/" + urllib.quote(target.get_uri())
211 assert (IFileNode.providedBy(target)
212 or IDirectoryNode.providedBy(target)
213 or IMutableFileNode.providedBy(target)), target
215 if IMutableFileNode.providedBy(target):
218 # add the filename to the uri_link url
219 uri_link += '?%s' % (urllib.urlencode({'filename': name}),)
221 # to prevent javascript in displayed .html files from stealing a
222 # secret directory URI from the URL, send the browser to a URI-based
223 # page that doesn't know about the directory at all
224 #dlurl = urllib.quote(name)
227 ctx.fillSlots("filename",
228 T.a(href=dlurl)[html.escape(name)])
229 ctx.fillSlots("type", "SSK")
231 ctx.fillSlots("size", "?")
233 text_plain_link = uri_link + "?filename=foo.txt"
234 text_plain_tag = T.a(href=text_plain_link)["text/plain"]
236 elif IFileNode.providedBy(target):
239 # add the filename to the uri_link url
240 uri_link += '?%s' % (urllib.urlencode({'filename': name}),)
242 # to prevent javascript in displayed .html files from stealing a
243 # secret directory URI from the URL, send the browser to a URI-based
244 # page that doesn't know about the directory at all
245 #dlurl = urllib.quote(name)
248 ctx.fillSlots("filename",
249 T.a(href=dlurl)[html.escape(name)])
250 ctx.fillSlots("type", "FILE")
252 ctx.fillSlots("size", target.get_size())
254 text_plain_link = uri_link + "?filename=foo.txt"
255 text_plain_tag = T.a(href=text_plain_link)["text/plain"]
257 elif IDirectoryNode.providedBy(target):
259 ctx.fillSlots("filename",
260 T.a(href=uri_link)[html.escape(name)])
261 if target.is_readonly():
265 ctx.fillSlots("type", dirtype)
266 ctx.fillSlots("size", "-")
267 text_plain_tag = None
269 childdata = [T.a(href="%s?t=json" % name)["JSON"], ", ",
270 T.a(href="%s?t=uri" % name)["URI"], ", ",
271 T.a(href="%s?t=readonly-uri" % name)["readonly-URI"],
274 childdata.extend([", ", text_plain_tag])
276 ctx.fillSlots("data", childdata)
279 checker = IClient(ctx).getServiceNamed("checker")
283 d = defer.maybeDeferred(checker.checker_results_for,
284 target.get_verifier())
285 def _got(checker_results):
286 recent_results = reversed(checker_results[-5:])
287 if IFileNode.providedBy(target):
289 ", ".join(["%d/%d" % (found, needed)
291 (needed, total, found, sharemap))
292 in recent_results]) +
294 elif IDirectoryNode.providedBy(target):
296 "".join([{True:"+",False:"-"}[res]
297 for (when, res) in recent_results]) +
300 results = "%d results" % len(checker_results)
306 # TODO: include a link to see more results, including timestamps
307 # TODO: use a sparkline
308 ctx.fillSlots("checker_results", results)
312 def render_forms(self, ctx, data):
313 if self._dirnode.is_readonly():
314 return T.div["No upload forms: directory is read-only"]
315 mkdir = T.form(action=".", method="post",
316 enctype="multipart/form-data")[
318 T.input(type="hidden", name="t", value="mkdir"),
319 T.input(type="hidden", name="when_done", value=url.here),
320 T.legend(class_="freeform-form-label")["Create a new directory"],
321 "New directory name: ",
322 T.input(type="text", name="name"), " ",
323 T.input(type="submit", value="Create"),
326 upload = T.form(action=".", method="post",
327 enctype="multipart/form-data")[
329 T.input(type="hidden", name="t", value="upload"),
330 T.input(type="hidden", name="when_done", value=url.here),
331 T.legend(class_="freeform-form-label")["Upload a file to this directory"],
332 "Choose a file to upload: ",
333 T.input(type="file", name="file", class_="freeform-input-file"),
335 T.input(type="submit", value="Upload"),
337 T.input(type="checkbox", name="mutable"),
340 mount = T.form(action=".", method="post",
341 enctype="multipart/form-data")[
343 T.input(type="hidden", name="t", value="uri"),
344 T.input(type="hidden", name="when_done", value=url.here),
345 T.legend(class_="freeform-form-label")["Attach a file or directory"
349 T.input(type="text", name="name"), " ",
350 "URI of new child: ",
351 T.input(type="text", name="uri"), " ",
352 T.input(type="submit", value="Attach"),
354 return [T.div(class_="freeform-form")[mkdir],
355 T.div(class_="freeform-form")[upload],
356 T.div(class_="freeform-form")[mount],
359 def build_overwrite(self, ctx, data):
361 if IMutableFileNode.providedBy(target) and not target.is_readonly():
362 action="/uri/" + urllib.quote(target.get_uri())
363 overwrite = T.form(action=action, method="post",
364 enctype="multipart/form-data")[
366 T.input(type="hidden", name="t", value="overwrite"),
367 T.input(type='hidden', name='name', value=name),
368 T.input(type='hidden', name='when_done', value=url.here),
369 T.legend(class_="freeform-form-label")["Overwrite"],
371 T.input(type="file", name="file", class_="freeform-input-file"),
373 T.input(type="submit", value="Overwrite")
375 return [T.div(class_="freeform-form")[overwrite],]
379 def render_results(self, ctx, data):
380 req = inevow.IRequest(ctx)
381 return get_arg(req, "results", "")
383 class WebDownloadTarget:
384 implements(IDownloadTarget, IConsumer)
385 def __init__(self, req, content_type, content_encoding, save_to_file):
387 self._content_type = content_type
388 self._content_encoding = content_encoding
390 self._producer = None
391 self._save_to_file = save_to_file
393 def registerProducer(self, producer, streaming):
394 self._req.registerProducer(producer, streaming)
395 def unregisterProducer(self):
396 self._req.unregisterProducer()
398 def open(self, size):
400 self._req.setHeader("content-type", self._content_type)
401 if self._content_encoding:
402 self._req.setHeader("content-encoding", self._content_encoding)
403 self._req.setHeader("content-length", str(size))
404 if self._save_to_file is not None:
405 # tell the browser to save the file rather display it
406 # TODO: quote save_to_file properly
407 self._req.setHeader("content-disposition",
408 'attachment; filename="%s"'
409 % self._save_to_file)
411 def write(self, data):
412 self._req.write(data)
418 # The content-type is already set, and the response code
419 # has already been sent, so we can't provide a clean error
420 # indication. We can emit text (which a browser might interpret
421 # as something else), and if we sent a Size header, they might
422 # notice that we've truncated the data. Keep the error message
423 # small to improve the chances of having our error response be
424 # shorter than the intended results.
426 # We don't have a lot of options, unfortunately.
427 self._req.write("problem during download\n")
429 # We haven't written anything yet, so we can provide a sensible
432 msg.replace("\n", "|")
433 self._req.setResponseCode(http.GONE, msg)
434 self._req.setHeader("content-type", "text/plain")
435 # TODO: HTML-formatted exception?
436 self._req.write(str(why))
439 def register_canceller(self, cb):
444 class FileDownloader(resource.Resource):
445 def __init__(self, filenode, name):
446 assert (IFileNode.providedBy(filenode)
447 or IMutableFileNode.providedBy(filenode))
448 self._filenode = filenode
451 def render(self, req):
452 gte = static.getTypeAndEncoding
453 type, encoding = gte(self._name,
454 static.File.contentTypes,
455 static.File.contentEncodings,
456 defaultType="text/plain")
458 if get_arg(req, "save", False):
459 # TODO: make the API specification clear: should "save=" or
460 # "save=false" count?
461 save_to_file = self._name
462 wdt = WebDownloadTarget(req, type, encoding, save_to_file)
463 d = self._filenode.download(wdt)
464 # exceptions during download are handled by the WebDownloadTarget
465 d.addErrback(lambda why: None)
466 return server.NOT_DONE_YET
468 class BlockingFileError(Exception):
469 """We cannot auto-create a parent directory, because there is a file in
471 class NoReplacementError(Exception):
472 """There was already a child by that name, and you asked me to not replace it"""
473 class NoLocalDirectoryError(Exception):
474 """The localdir= directory didn't exist"""
476 LOCALHOST = "127.0.0.1"
478 class NeedLocalhostError:
479 implements(inevow.IResource)
481 def renderHTTP(self, ctx):
482 req = inevow.IRequest(ctx)
483 req.setResponseCode(http.FORBIDDEN)
484 req.setHeader("content-type", "text/plain")
485 return "localfile= or localdir= requires a local connection"
487 class NeedAbsolutePathError:
488 implements(inevow.IResource)
490 def renderHTTP(self, ctx):
491 req = inevow.IRequest(ctx)
492 req.setResponseCode(http.FORBIDDEN)
493 req.setHeader("content-type", "text/plain")
494 return "localfile= or localdir= requires an absolute path"
496 class LocalAccessDisabledError:
497 implements(inevow.IResource)
499 def renderHTTP(self, ctx):
500 req = inevow.IRequest(ctx)
501 req.setResponseCode(http.FORBIDDEN)
502 req.setHeader("content-type", "text/plain")
503 return "local file access is disabled"
506 class LocalFileDownloader(resource.Resource):
507 def __init__(self, filenode, local_filename):
508 self._local_filename = local_filename
510 self._filenode = filenode
512 def render(self, req):
513 target = download.FileName(self._local_filename)
514 d = self._filenode.download(target)
516 req.write(self._filenode.get_uri())
519 return server.NOT_DONE_YET
522 class FileJSONMetadata(rend.Page):
523 def __init__(self, filenode):
524 self._filenode = filenode
526 def renderHTTP(self, ctx):
527 req = inevow.IRequest(ctx)
528 req.setHeader("content-type", "text/plain")
529 return self.renderNode(self._filenode)
531 def renderNode(self, filenode):
532 file_uri = filenode.get_uri()
535 'size': filenode.get_size(),
537 return simplejson.dumps(data, indent=1)
539 class FileURI(FileJSONMetadata):
540 def renderNode(self, filenode):
541 file_uri = filenode.get_uri()
544 class FileReadOnlyURI(FileJSONMetadata):
545 def renderNode(self, filenode):
546 if filenode.is_readonly():
547 return filenode.get_uri()
549 return filenode.get_readonly().get_uri()
551 class DirnodeWalkerMixin:
552 """Visit all nodes underneath (and including) the rootnode, one at a
553 time. For each one, call the visitor. The visitor will see the
554 IDirectoryNode before it sees any of the IFileNodes inside. If the
555 visitor returns a Deferred, I do not call the visitor again until it has
559 ## def _walk_if_we_could_use_generators(self, rootnode, rootpath=()):
560 ## # this is what we'd be doing if we didn't have the Deferreds and
561 ## # thus could use generators
562 ## yield rootpath, rootnode
563 ## for childname, childnode in rootnode.list().items():
564 ## childpath = rootpath + (childname,)
565 ## if IFileNode.providedBy(childnode):
566 ## yield childpath, childnode
567 ## elif IDirectoryNode.providedBy(childnode):
568 ## for res in self._walk_if_we_could_use_generators(childnode,
572 def walk(self, rootnode, visitor, rootpath=()):
574 def _listed(listing):
575 return listing.items()
576 d.addCallback(_listed)
577 d.addCallback(self._handle_items, visitor, rootpath)
580 def _handle_items(self, items, visitor, rootpath):
583 childname, (childnode, metadata) = items[0]
584 childpath = rootpath + (childname,)
585 d = defer.maybeDeferred(visitor, childpath, childnode, metadata)
586 if IDirectoryNode.providedBy(childnode):
587 d.addCallback(lambda res: self.walk(childnode, visitor, childpath))
588 d.addCallback(lambda res:
589 self._handle_items(items[1:], visitor, rootpath))
592 class LocalDirectoryDownloader(resource.Resource, DirnodeWalkerMixin):
593 def __init__(self, dirnode, localdir):
594 self._dirnode = dirnode
595 self._localdir = localdir
597 def _handle(self, path, node, metadata):
598 localfile = os.path.join(self._localdir, os.sep.join(path))
599 if IDirectoryNode.providedBy(node):
600 fileutil.make_dirs(localfile)
601 elif IFileNode.providedBy(node):
602 target = download.FileName(localfile)
603 return node.download(target)
605 def render(self, req):
606 d = self.walk(self._dirnode, self._handle)
608 req.setHeader("content-type", "text/plain")
609 return "operation complete"
613 class DirectoryJSONMetadata(rend.Page):
614 def __init__(self, dirnode):
615 self._dirnode = dirnode
617 def renderHTTP(self, ctx):
618 req = inevow.IRequest(ctx)
619 req.setHeader("content-type", "text/plain")
620 return self.renderNode(self._dirnode)
622 def renderNode(self, node):
626 for name, (childnode, metadata) in children.iteritems():
627 if IFileNode.providedBy(childnode):
628 kiduri = childnode.get_uri()
629 kiddata = ("filenode",
631 'size': childnode.get_size(),
634 assert IDirectoryNode.providedBy(childnode), (childnode, children,)
635 kiddata = ("dirnode",
636 {'ro_uri': childnode.get_readonly_uri(),
638 if not childnode.is_readonly():
639 kiddata[1]['rw_uri'] = childnode.get_uri()
641 contents = { 'children': kids,
642 'ro_uri': node.get_readonly_uri(),
644 if not node.is_readonly():
645 contents['rw_uri'] = node.get_uri()
646 data = ("dirnode", contents)
647 return simplejson.dumps(data, indent=1)
651 class DirectoryURI(DirectoryJSONMetadata):
652 def renderNode(self, node):
653 return node.get_uri()
655 class DirectoryReadonlyURI(DirectoryJSONMetadata):
656 def renderNode(self, node):
657 return node.get_readonly_uri()
659 class RenameForm(rend.Page):
661 docFactory = getxmlfile("rename-form.xhtml")
663 def __init__(self, rootname, dirnode, dirpath):
664 self._rootname = rootname
665 self._dirnode = dirnode
666 self._dirpath = dirpath
668 def dirpath_as_string(self):
669 return "/" + "/".join(self._dirpath)
671 def render_title(self, ctx, data):
672 return ctx.tag["Directory '%s':" % self.dirpath_as_string()]
674 def render_header(self, ctx, data):
675 parent_directories = ("<%s>" % self._rootname,) + self._dirpath
676 num_dirs = len(parent_directories)
678 header = [ "Rename in directory '",
679 "<%s>/" % self._rootname,
680 "/".join(self._dirpath),
683 if self._dirnode.is_readonly():
684 header.append(" (readonly)")
685 return ctx.tag[header]
687 def render_when_done(self, ctx, data):
688 return T.input(type="hidden", name="when_done", value=url.here)
690 def render_get_name(self, ctx, data):
691 req = inevow.IRequest(ctx)
692 name = get_arg(req, "name", "")
693 ctx.tag.attributes['value'] = name
696 class POSTHandler(rend.Page):
697 def __init__(self, node, replace):
699 self._replace = replace
701 def _check_replacement(self, name):
703 return defer.succeed(None)
704 d = self._node.has_child(name)
707 raise NoReplacementError("There was already a child by that "
708 "name, and you asked me to not "
714 def renderHTTP(self, ctx):
715 req = inevow.IRequest(ctx)
717 t = get_arg(req, "t")
720 name = get_arg(req, "name", None)
721 if name and "/" in name:
722 req.setResponseCode(http.BAD_REQUEST)
723 req.setHeader("content-type", "text/plain")
724 return "name= may not contain a slash"
727 # we allow the user to delete an empty-named file, but not to create
728 # them, since that's an easy and confusing mistake to make
730 when_done = get_arg(req, "when_done", None)
731 if not boolean_of_arg(get_arg(req, "replace", "true")):
732 self._replace = False
736 raise RuntimeError("mkdir requires a name")
737 d = self._check_replacement(name)
738 d.addCallback(lambda res: self._node.create_empty_directory(name))
739 d.addCallback(lambda res: "directory created")
742 raise RuntimeError("set-uri requires a name")
743 newuri = get_arg(req, "uri")
744 assert newuri is not None
745 d = self._check_replacement(name)
746 d.addCallback(lambda res: self._node.set_uri(name, newuri))
747 d.addCallback(lambda res: newuri)
750 # apparently an <input type="hidden" name="name" value="">
751 # won't show up in the resulting encoded form.. the 'name'
752 # field is completely missing. So to allow deletion of an
753 # empty file, we have to pretend that None means ''. The only
754 # downide of this is a slightly confusing error message if
755 # someone does a POST without a name= field. For our own HTML
756 # thisn't a big deal, because we create the 'delete' POST
759 d = self._node.delete(name)
760 d.addCallback(lambda res: "thing deleted")
762 from_name = 'from_name' in req.fields and req.fields["from_name"].value
763 if from_name is not None:
764 from_name = from_name.strip()
765 to_name = 'to_name' in req.fields and req.fields["to_name"].value
766 if to_name is not None:
767 to_name = to_name.strip()
768 if not from_name or not to_name:
769 raise RuntimeError("rename requires from_name and to_name")
770 if not IDirectoryNode.providedBy(self._node):
771 raise RuntimeError("rename must only be called on directories")
772 for k,v in [ ('from_name', from_name), ('to_name', to_name) ]:
774 req.setResponseCode(http.BAD_REQUEST)
775 req.setHeader("content-type", "text/plain")
776 return "%s= may not contain a slash" % (k,)
777 d = self._check_replacement(to_name)
778 d.addCallback(lambda res: self._node.get(from_name))
780 uri = child.get_uri()
781 # now actually do the rename
782 return self._node.set_uri(to_name, uri)
783 d.addCallback(add_dest)
785 return self._node.delete(from_name)
786 d.addCallback(rm_src)
787 d.addCallback(lambda res: "thing renamed")
790 if "mutable" in req.fields:
791 contents = req.fields["file"]
792 name = name or contents.filename
796 raise RuntimeError("upload-mutable requires a name")
797 # SDMF: files are small, and we can only upload data.
798 contents.file.seek(0)
799 data = contents.file.read()
800 #uploadable = FileHandle(contents.file)
801 d = self._check_replacement(name)
802 d.addCallback(lambda res: self._node.has_child(name))
803 def _checked(present):
805 # modify the existing one instead of creating a new
807 d2 = self._node.get(name)
808 def _got_newnode(newnode):
809 d3 = newnode.replace(data)
810 d3.addCallback(lambda res: newnode.get_uri())
812 d2.addCallback(_got_newnode)
814 d2 = IClient(ctx).create_mutable_file(data)
815 def _uploaded(newnode):
816 d1 = self._node.set_node(name, newnode)
817 d1.addCallback(lambda res: newnode.get_uri())
819 d2.addCallback(_uploaded)
821 d.addCallback(_checked)
823 contents = req.fields["file"]
824 name = name or contents.filename
828 raise RuntimeError("upload requires a name")
829 uploadable = FileHandle(contents.file)
830 d = self._check_replacement(name)
831 d.addCallback(lambda res: self._node.add_file(name, uploadable))
833 return newnode.get_uri()
836 elif t == "overwrite":
837 contents = req.fields["file"]
838 # SDMF: files are small, and we can only upload data.
839 contents.file.seek(0)
840 data = contents.file.read()
841 # TODO: 'name' handling needs review
842 d = defer.succeed(self._node)
843 def _got_child_overwrite(child_node):
844 child_node.replace(data)
845 return child_node.get_uri()
846 d.addCallback(_got_child_overwrite)
849 d = self._node.get(name)
850 def _got_child_check(child_node):
851 d2 = child_node.check()
853 log.msg("checked %s, results %s" % (child_node, res))
855 d2.addCallback(_done)
857 d.addCallback(_got_child_check)
860 return "BAD t=%s" % t
862 d.addCallback(lambda res: url.URL.fromString(when_done))
863 def _check_replacement(f):
864 # TODO: make this more human-friendly: maybe send them to the
865 # when_done page but with an extra query-arg that will display
866 # the error message in a big box at the top of the page. The
867 # directory page that when_done= usually points to accepts a
868 # result= argument.. use that.
869 f.trap(NoReplacementError)
870 req.setResponseCode(http.CONFLICT)
871 req.setHeader("content-type", "text/plain")
873 d.addErrback(_check_replacement)
876 class DELETEHandler(rend.Page):
877 def __init__(self, node, name):
881 def renderHTTP(self, ctx):
882 req = inevow.IRequest(ctx)
883 d = self._node.delete(self._name)
885 # what should this return??
886 return "%s deleted" % self._name
888 def _trap_missing(f):
890 req.setResponseCode(http.NOT_FOUND)
891 req.setHeader("content-type", "text/plain")
892 return "no such child %s" % self._name
893 d.addErrback(_trap_missing)
896 class PUTHandler(rend.Page):
897 def __init__(self, node, path, t, localfile, localdir, replace):
901 self._localfile = localfile
902 self._localdir = localdir
903 self._replace = replace
905 def renderHTTP(self, ctx):
906 req = inevow.IRequest(ctx)
908 localfile = self._localfile
909 localdir = self._localdir
911 if t == "upload" and not (localfile or localdir):
912 req.setResponseCode(http.BAD_REQUEST)
913 req.setHeader("content-type", "text/plain")
914 return "t=upload requires localfile= or localdir="
916 # we must traverse the path, creating new directories as necessary
917 d = self._get_or_create_directories(self._node, self._path[:-1])
918 name = self._path[-1]
919 d.addCallback(self._check_replacement, name, self._replace)
922 d.addCallback(self._upload_localfile, localfile, name)
926 d.addCallback(self._get_or_create_directories, self._path[-1:])
927 d.addCallback(self._upload_localdir, localdir)
929 d.addCallback(self._attach_uri, req.content, name)
931 d.addCallback(self._mkdir, name)
933 d.addCallback(self._upload_file, req.content, name)
935 def _transform_error(f):
936 errors = {BlockingFileError: http.BAD_REQUEST,
937 NoReplacementError: http.CONFLICT,
938 NoLocalDirectoryError: http.BAD_REQUEST,
940 for k,v in errors.items():
942 req.setResponseCode(v)
943 req.setHeader("content-type", "text/plain")
946 d.addErrback(_transform_error)
949 def _get_or_create_directories(self, node, path):
950 if not IDirectoryNode.providedBy(node):
951 # unfortunately it is too late to provide the name of the
952 # blocking directory in the error message.
953 raise BlockingFileError("cannot create directory because there "
954 "is a file in the way")
956 return defer.succeed(node)
957 d = node.get(path[0])
958 def _maybe_create(f):
960 return node.create_empty_directory(path[0])
961 d.addErrback(_maybe_create)
962 d.addCallback(self._get_or_create_directories, path[1:])
965 def _check_replacement(self, node, name, replace):
968 d = node.has_child(name)
971 raise NoReplacementError("There was already a child by that "
972 "name, and you asked me to not "
978 def _mkdir(self, node, name):
979 d = node.create_empty_directory(name)
981 return newnode.get_uri()
985 def _upload_file(self, node, contents, name):
986 uploadable = FileHandle(contents)
987 d = node.add_file(name, uploadable)
989 log.msg("webish upload complete")
990 return filenode.get_uri()
994 def _upload_localfile(self, node, localfile, name):
995 uploadable = FileName(localfile)
996 d = node.add_file(name, uploadable)
997 d.addCallback(lambda filenode: filenode.get_uri())
1000 def _attach_uri(self, parentnode, contents, name):
1001 newuri = contents.read().strip()
1002 d = parentnode.set_uri(name, newuri)
1005 d.addCallback(_done)
1008 def _upload_localdir(self, node, localdir):
1009 # build up a list of files to upload
1012 msg = "No files to upload! %s is empty" % localdir
1013 if not os.path.exists(localdir):
1014 msg = "%s doesn't exist!" % localdir
1015 raise NoLocalDirectoryError(msg)
1016 for root, dirs, files in os.walk(localdir):
1017 if root == localdir:
1020 relative_root = root[len(localdir)+1:]
1021 path = tuple(relative_root.split(os.sep))
1023 all_dirs.append(path + (d,))
1025 all_files.append(path + (f,))
1026 d = defer.succeed(msg)
1027 for dir in all_dirs:
1029 d.addCallback(self._makedir, node, dir)
1031 d.addCallback(self._upload_one_file, node, localdir, f)
1034 def _makedir(self, res, node, dir):
1035 d = defer.succeed(None)
1036 # get the parent. As long as os.walk gives us parents before
1037 # children, this ought to work
1038 d.addCallback(lambda res: node.get_child_at_path(dir[:-1]))
1039 # then create the child directory
1040 d.addCallback(lambda parent: parent.create_empty_directory(dir[-1]))
1043 def _upload_one_file(self, res, node, localdir, f):
1044 # get the parent. We can be sure this exists because we already
1045 # went through and created all the directories we require.
1046 localfile = os.path.join(localdir, *f)
1047 d = node.get_child_at_path(f[:-1])
1048 d.addCallback(self._upload_localfile, localfile, f[-1])
1052 class Manifest(rend.Page):
1053 docFactory = getxmlfile("manifest.xhtml")
1054 def __init__(self, dirnode, dirpath):
1055 self._dirnode = dirnode
1056 self._dirpath = dirpath
1058 def dirpath_as_string(self):
1059 return "/" + "/".join(self._dirpath)
1061 def render_title(self, ctx):
1062 return T.title["Manifest of %s" % self.dirpath_as_string()]
1064 def render_header(self, ctx):
1065 return T.p["Manifest of %s" % self.dirpath_as_string()]
1067 def data_items(self, ctx, data):
1068 return self._dirnode.build_manifest()
1070 def render_row(self, ctx, refresh_cap):
1071 ctx.fillSlots("refresh_capability", refresh_cap)
1075 implements(inevow.IResource)
1076 def renderHTTP(self, ctx):
1077 req = inevow.IRequest(ctx)
1078 req.setResponseCode(http.BAD_REQUEST)
1079 req.setHeader("content-type", "text/plain")
1082 def child_error(text):
1087 class VDrive(rend.Page):
1089 def __init__(self, node, name):
1093 def get_child_at_path(self, path):
1095 return self.node.get_child_at_path(path)
1096 return defer.succeed(self.node)
1098 def locateChild(self, ctx, segments):
1099 req = inevow.IRequest(ctx)
1103 t = get_arg(req, "t", "")
1104 localfile = get_arg(req, "localfile", None)
1105 if localfile is not None:
1106 if localfile != os.path.abspath(localfile):
1107 return NeedAbsolutePathError(), ()
1108 localdir = get_arg(req, "localdir", None)
1109 if localdir is not None:
1110 if localdir != os.path.abspath(localdir):
1111 return NeedAbsolutePathError(), ()
1112 if localfile or localdir:
1113 if not ILocalAccess(ctx).local_access_is_allowed():
1114 return LocalAccessDisabledError(), ()
1115 if req.getHost().host != LOCALHOST:
1116 return NeedLocalhostError(), ()
1117 # TODO: think about clobbering/revealing config files and node secrets
1119 replace = boolean_of_arg(get_arg(req, "replace", "true"))
1122 # the node must exist, and our operation will be performed on the
1124 d = self.get_child_at_path(path)
1125 def file_or_dir(node):
1126 if (IFileNode.providedBy(node)
1127 or IMutableFileNode.providedBy(node)):
1128 filename = "unknown"
1131 filename = get_arg(req, "filename", filename)
1134 # write contents to a local file
1135 return LocalFileDownloader(node, localfile), ()
1136 # send contents as the result
1137 return FileDownloader(node, filename), ()
1139 # send contents as the result
1140 return FileDownloader(node, filename), ()
1142 return FileJSONMetadata(node), ()
1144 return FileURI(node), ()
1145 elif t == "readonly-uri":
1146 return FileReadOnlyURI(node), ()
1148 return child_error("bad t=%s" % t)
1149 elif IDirectoryNode.providedBy(node):
1152 # recursive download to a local directory
1153 return LocalDirectoryDownloader(node, localdir), ()
1154 return child_error("t=download requires localdir=")
1156 # send an HTML representation of the directory
1157 return Directory(self.name, node, path), ()
1159 return DirectoryJSONMetadata(node), ()
1161 return DirectoryURI(node), ()
1162 elif t == "readonly-uri":
1163 return DirectoryReadonlyURI(node), ()
1164 elif t == "manifest":
1165 return Manifest(node, path), ()
1166 elif t == 'rename-form':
1167 return RenameForm(self.name, node, path), ()
1169 return child_error("bad t=%s" % t)
1171 return child_error("unknown node type")
1172 d.addCallback(file_or_dir)
1173 elif method == "POST":
1174 # the node must exist, and our operation will be performed on the
1176 d = self.get_child_at_path(path)
1177 def _got_POST(node):
1178 return POSTHandler(node, replace), ()
1179 d.addCallback(_got_POST)
1180 elif method == "DELETE":
1181 # the node must exist, and our operation will be performed on its
1183 assert path # you can't delete the root
1184 d = self.get_child_at_path(path[:-1])
1185 def _got_DELETE(node):
1186 return DELETEHandler(node, path[-1]), ()
1187 d.addCallback(_got_DELETE)
1188 elif method in ("PUT",):
1189 # the node may or may not exist, and our operation may involve
1190 # all the ancestors of the node.
1191 return PUTHandler(self.node, path, t, localfile, localdir, replace), ()
1193 return rend.NotFound
1196 class URIPUTHandler(rend.Page):
1197 def renderHTTP(self, ctx):
1198 req = inevow.IRequest(ctx)
1199 assert req.method == "PUT"
1201 t = get_arg(req, "t", "")
1204 # "PUT /uri", to create an unlinked file. This is like PUT but
1205 # without the associated set_uri.
1206 uploadable = FileHandle(req.content)
1207 d = IClient(ctx).upload(uploadable)
1208 d.addCallback(lambda results: results.uri)
1209 # that fires with the URI of the new file
1213 # "PUT /uri?t=mkdir", to create an unlinked directory.
1214 d = IClient(ctx).create_empty_dirnode()
1215 d.addCallback(lambda dirnode: dirnode.get_uri())
1216 # XXX add redirect_to_result
1219 req.setResponseCode(http.BAD_REQUEST)
1220 req.setHeader("content-type", "text/plain")
1221 return "/uri only accepts PUT and PUT?t=mkdir"
1223 class URIPOSTHandler(rend.Page):
1224 def renderHTTP(self, ctx):
1225 req = inevow.IRequest(ctx)
1226 assert req.method == "POST"
1228 t = get_arg(req, "t", "").strip()
1230 if t in ("", "upload"):
1231 # "POST /uri", to create an unlinked file.
1232 fileobj = req.fields["file"].file
1233 uploadable = FileHandle(fileobj)
1234 d = IClient(ctx).upload(uploadable)
1235 d.addCallback(lambda results: results.uri)
1236 # that fires with the URI of the new file
1240 # "POST /uri?t=mkdir", to create an unlinked directory.
1241 d = IClient(ctx).create_empty_dirnode()
1242 redirect = get_arg(req, "redirect_to_result", "false")
1243 if boolean_of_arg(redirect):
1244 def _then_redir(res):
1245 new_url = "uri/" + urllib.quote(res.get_uri())
1246 req.setResponseCode(http.SEE_OTHER) # 303
1247 req.setHeader('location', new_url)
1250 d.addCallback(_then_redir)
1252 d.addCallback(lambda dirnode: dirnode.get_uri())
1255 req.setResponseCode(http.BAD_REQUEST)
1256 req.setHeader("content-type", "text/plain")
1257 err = "/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, and POST?t=mkdir"
1261 class Root(rend.Page):
1264 docFactory = getxmlfile("welcome.xhtml")
1266 def locateChild(self, ctx, segments):
1267 client = IClient(ctx)
1268 req = inevow.IRequest(ctx)
1270 segments = list(segments) # XXX HELP I AM YUCKY!
1271 while segments and not segments[-1]:
1275 segments = tuple(segments)
1277 if segments[0] == "uri":
1278 if len(segments) == 1 or segments[1] == '':
1279 uri = get_arg(req, "uri", None)
1281 there = url.URL.fromContext(ctx)
1282 there = there.clear("uri")
1283 there = there.child("uri").child(uri)
1285 if len(segments) == 1:
1287 if req.method == "PUT":
1288 # either "PUT /uri" to create an unlinked file, or
1289 # "PUT /uri?t=mkdir" to create an unlinked directory
1290 return URIPUTHandler(), ()
1291 elif req.method == "POST":
1292 # "POST /uri?t=upload&file=newfile" to upload an unlinked
1293 # file or "POST /uri?t=mkdir" to create a new directory
1294 return URIPOSTHandler(), ()
1295 if len(segments) < 2:
1296 return rend.NotFound
1298 d = defer.maybeDeferred(client.create_node_from_uri, uri)
1299 d.addCallback(lambda node: VDrive(node, uri))
1300 d.addCallback(lambda vd: vd.locateChild(ctx, segments[2:]))
1301 def _trap_KeyError(f):
1303 return rend.FourOhFour(), ()
1304 d.addErrback(_trap_KeyError)
1306 elif segments[0] == "xmlrpc":
1307 raise NotImplementedError()
1308 return rend.Page.locateChild(self, ctx, segments)
1310 child_webform_css = webform.defaultCSS
1311 child_tahoe_css = nevow_File(resource_filename('allmydata.web', 'tahoe.css'))
1313 child_provisioning = provisioning.ProvisioningTool()
1315 def data_version(self, ctx, data):
1316 return get_package_versions_string()
1317 def data_import_path(self, ctx, data):
1318 return str(allmydata)
1319 def data_my_nodeid(self, ctx, data):
1320 return idlib.nodeid_b2a(IClient(ctx).nodeid)
1321 def data_storage(self, ctx, data):
1322 client = IClient(ctx)
1324 ss = client.getServiceNamed("storage")
1326 return "Not running"
1327 allocated = ss.allocated_size()
1328 return "about %d bytes allocated" % allocated
1330 def data_introducer_furl(self, ctx, data):
1331 return IClient(ctx).introducer_furl
1332 def data_connected_to_introducer(self, ctx, data):
1333 if IClient(ctx).connected_to_introducer():
1337 def data_helper_furl(self, ctx, data):
1339 uploader = IClient(ctx).getServiceNamed("uploader")
1342 furl, connected = uploader.get_helper_info()
1344 def data_connected_to_helper(self, ctx, data):
1346 uploader = IClient(ctx).getServiceNamed("uploader")
1348 return "no" # we don't even have an Uploader
1349 furl, connected = uploader.get_helper_info()
1354 def data_known_storage_servers(self, ctx, data):
1355 ic = IClient(ctx).introducer_client
1357 for c in ic.get_all_connectors().values()
1358 if c.service_name == "storage"]
1361 def data_connected_storage_servers(self, ctx, data):
1362 ic = IClient(ctx).introducer_client
1363 return len(ic.get_all_connections_for("storage"))
1365 def data_services(self, ctx, data):
1366 ic = IClient(ctx).introducer_client
1367 c = [ (service_name, nodeid, rsc)
1368 for (nodeid, service_name), rsc
1369 in ic.get_all_connectors().items() ]
1373 def render_service_row(self, ctx, data):
1374 (service_name, nodeid, rsc) = data
1375 ctx.fillSlots("peerid", "%s %s" % (idlib.nodeid_b2a(nodeid),
1378 rhost = rsc.remote_host
1379 if nodeid == IClient(ctx).nodeid:
1380 rhost_s = "(loopback)"
1381 elif isinstance(rhost, address.IPv4Address):
1382 rhost_s = "%s:%d" % (rhost.host, rhost.port)
1384 rhost_s = str(rhost)
1385 connected = "Yes: to " + rhost_s
1386 since = rsc.last_connect_time
1389 since = rsc.last_loss_time
1391 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
1392 ctx.fillSlots("connected", connected)
1393 ctx.fillSlots("since", time.strftime(TIME_FORMAT, time.localtime(since)))
1394 ctx.fillSlots("announced", time.strftime(TIME_FORMAT,
1395 time.localtime(rsc.announcement_time)))
1396 ctx.fillSlots("version", rsc.version)
1397 ctx.fillSlots("service_name", rsc.service_name)
1401 # this is a form where users can download files by URI
1402 def render_download_form(self, ctx, data):
1403 form = T.form(action="uri", method="get",
1404 enctype="multipart/form-data")[
1406 T.legend(class_="freeform-form-label")["download a file"],
1407 "URI of file to download: ",
1408 T.input(type="text", name="uri"), " ",
1409 "Filename to download as: ",
1410 T.input(type="text", name="filename"), " ",
1411 T.input(type="submit", value="download"),
1415 # this is a form where users can create new directories
1416 def render_mkdir_form(self, ctx, data):
1417 form = T.form(action="uri", method="post",
1418 enctype="multipart/form-data")[
1420 T.legend(class_="freeform-form-label")["create a directory"],
1421 T.input(type="hidden", name="t", value="mkdir"),
1422 T.input(type="hidden", name="redirect_to_result", value="true"),
1423 T.input(type="submit", value="create"),
1429 implements(ILocalAccess)
1431 self.local_access = False
1432 def local_access_is_allowed(self):
1433 return self.local_access
1435 class WebishServer(service.MultiService):
1438 def __init__(self, webport, nodeurl_path=None):
1439 service.MultiService.__init__(self)
1440 self.webport = webport
1442 self.site = site = appserver.NevowSite(self.root)
1443 self.site.requestFactory = MyRequest
1444 self.allow_local = LocalAccess()
1445 self.site.remember(self.allow_local, ILocalAccess)
1446 s = strports.service(webport, site)
1447 s.setServiceParent(self)
1448 self.listener = s # stash it so the tests can query for the portnum
1449 self._started = defer.Deferred()
1451 self._started.addCallback(self._write_nodeurl_file, nodeurl_path)
1453 def allow_local_access(self, enable=True):
1454 self.allow_local.local_access = enable
1456 def startService(self):
1457 service.MultiService.startService(self)
1458 # to make various services available to render_* methods, we stash a
1459 # reference to the client on the NevowSite. This will be available by
1460 # adapting the 'context' argument to a special marker interface named
1462 self.site.remember(self.parent, IClient)
1463 # I thought you could do the same with an existing interface, but
1464 # apparently 'ISite' does not exist
1465 #self.site._client = self.parent
1466 self._started.callback(None)
1468 def _write_nodeurl_file(self, junk, nodeurl_path):
1469 # what is our webport?
1471 if isinstance(s, internet.TCPServer):
1472 base_url = "http://localhost:%d" % s._port.getHost().port
1473 elif isinstance(s, internet.SSLServer):
1474 base_url = "https://localhost:%d" % s._port.getHost().port
1478 f = open(nodeurl_path, 'wb')
1479 # this file is world-readable
1480 f.write(base_url + "\n")