2 from base64 import b32encode
4 from twisted.application import service, strports, internet
5 from twisted.web import static, resource, server, html, http
6 from twisted.python import log
7 from twisted.internet import defer
8 from twisted.internet.interfaces import IConsumer
9 from nevow import inevow, rend, loaders, appserver, url, tags as T
10 from nevow.static import File as nevow_File # TODO: merge with static.File?
11 from allmydata.util import fileutil
13 from allmydata.interfaces import IDownloadTarget, IDirectoryNode, IFileNode, \
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 subdir_url = urllib.quote(name)
260 ctx.fillSlots("filename",
261 T.a(href=subdir_url)[html.escape(name)])
262 if target.is_readonly():
266 ctx.fillSlots("type", dirtype)
267 ctx.fillSlots("size", "-")
268 text_plain_tag = None
270 childdata = [T.a(href="%s?t=json" % name)["JSON"], ", ",
271 T.a(href="%s?t=uri" % name)["URI"], ", ",
272 T.a(href="%s?t=readonly-uri" % name)["readonly-URI"], ", ",
273 T.a(href=uri_link)["URI-link"],
276 childdata.extend([", ", text_plain_tag])
278 ctx.fillSlots("data", childdata)
281 checker = IClient(ctx).getServiceNamed("checker")
285 d = defer.maybeDeferred(checker.checker_results_for,
286 target.get_verifier())
287 def _got(checker_results):
288 recent_results = reversed(checker_results[-5:])
289 if IFileNode.providedBy(target):
291 ", ".join(["%d/%d" % (found, needed)
293 (needed, total, found, sharemap))
294 in recent_results]) +
296 elif IDirectoryNode.providedBy(target):
298 "".join([{True:"+",False:"-"}[res]
299 for (when, res) in recent_results]) +
302 results = "%d results" % len(checker_results)
308 # TODO: include a link to see more results, including timestamps
309 # TODO: use a sparkline
310 ctx.fillSlots("checker_results", results)
314 def render_forms(self, ctx, data):
315 if self._dirnode.is_readonly():
316 return T.div["No upload forms: directory is read-only"]
317 mkdir = T.form(action=".", method="post",
318 enctype="multipart/form-data")[
320 T.input(type="hidden", name="t", value="mkdir"),
321 T.input(type="hidden", name="when_done", value=url.here),
322 T.legend(class_="freeform-form-label")["Create a new directory"],
323 "New directory name: ",
324 T.input(type="text", name="name"), " ",
325 T.input(type="submit", value="Create"),
328 upload = T.form(action=".", method="post",
329 enctype="multipart/form-data")[
331 T.input(type="hidden", name="t", value="upload"),
332 T.input(type="hidden", name="when_done", value=url.here),
333 T.legend(class_="freeform-form-label")["Upload a file to this directory"],
334 "Choose a file to upload: ",
335 T.input(type="file", name="file", class_="freeform-input-file"),
337 T.input(type="submit", value="Upload"),
339 T.input(type="checkbox", name="mutable"),
342 mount = T.form(action=".", method="post",
343 enctype="multipart/form-data")[
345 T.input(type="hidden", name="t", value="uri"),
346 T.input(type="hidden", name="when_done", value=url.here),
347 T.legend(class_="freeform-form-label")["Attach a file or directory"
351 T.input(type="text", name="name"), " ",
352 "URI of new child: ",
353 T.input(type="text", name="uri"), " ",
354 T.input(type="submit", value="Attach"),
356 return [T.div(class_="freeform-form")[mkdir],
357 T.div(class_="freeform-form")[upload],
358 T.div(class_="freeform-form")[mount],
361 def build_overwrite(self, ctx, data):
363 if IMutableFileNode.providedBy(target) and not target.is_readonly():
364 action="/uri/" + urllib.quote(target.get_uri())
365 overwrite = T.form(action=action, method="post",
366 enctype="multipart/form-data")[
368 T.input(type="hidden", name="t", value="overwrite"),
369 T.input(type='hidden', name='name', value=name),
370 T.input(type='hidden', name='when_done', value=url.here),
371 T.legend(class_="freeform-form-label")["Overwrite"],
373 T.input(type="file", name="file", class_="freeform-input-file"),
375 T.input(type="submit", value="Overwrite")
377 return [T.div(class_="freeform-form")[overwrite],]
381 def render_results(self, ctx, data):
382 req = inevow.IRequest(ctx)
383 return get_arg(req, "results", "")
385 class WebDownloadTarget:
386 implements(IDownloadTarget, IConsumer)
387 def __init__(self, req, content_type, content_encoding, save_to_file):
389 self._content_type = content_type
390 self._content_encoding = content_encoding
392 self._producer = None
393 self._save_to_file = save_to_file
395 def registerProducer(self, producer, streaming):
396 self._req.registerProducer(producer, streaming)
397 def unregisterProducer(self):
398 self._req.unregisterProducer()
400 def open(self, size):
402 self._req.setHeader("content-type", self._content_type)
403 if self._content_encoding:
404 self._req.setHeader("content-encoding", self._content_encoding)
405 self._req.setHeader("content-length", str(size))
406 if self._save_to_file is not None:
407 # tell the browser to save the file rather display it
408 # TODO: quote save_to_file properly
409 self._req.setHeader("content-disposition",
410 'attachment; filename="%s"'
411 % self._save_to_file)
413 def write(self, data):
414 self._req.write(data)
420 # The content-type is already set, and the response code
421 # has already been sent, so we can't provide a clean error
422 # indication. We can emit text (which a browser might interpret
423 # as something else), and if we sent a Size header, they might
424 # notice that we've truncated the data. Keep the error message
425 # small to improve the chances of having our error response be
426 # shorter than the intended results.
428 # We don't have a lot of options, unfortunately.
429 self._req.write("problem during download\n")
431 # We haven't written anything yet, so we can provide a sensible
434 msg.replace("\n", "|")
435 self._req.setResponseCode(http.GONE, msg)
436 self._req.setHeader("content-type", "text/plain")
437 # TODO: HTML-formatted exception?
438 self._req.write(str(why))
441 def register_canceller(self, cb):
446 class FileDownloader(resource.Resource):
447 def __init__(self, filenode, name):
448 assert (IFileNode.providedBy(filenode)
449 or IMutableFileNode.providedBy(filenode))
450 self._filenode = filenode
453 def render(self, req):
454 gte = static.getTypeAndEncoding
455 type, encoding = gte(self._name,
456 static.File.contentTypes,
457 static.File.contentEncodings,
458 defaultType="text/plain")
460 if get_arg(req, "save", False):
461 # TODO: make the API specification clear: should "save=" or
462 # "save=false" count?
463 save_to_file = self._name
464 wdt = WebDownloadTarget(req, type, encoding, save_to_file)
465 d = self._filenode.download(wdt)
466 # exceptions during download are handled by the WebDownloadTarget
467 d.addErrback(lambda why: None)
468 return server.NOT_DONE_YET
470 class BlockingFileError(Exception):
471 """We cannot auto-create a parent directory, because there is a file in
473 class NoReplacementError(Exception):
474 """There was already a child by that name, and you asked me to not replace it"""
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)
934 def _check_blocking(f):
935 f.trap(BlockingFileError)
936 req.setResponseCode(http.BAD_REQUEST)
937 req.setHeader("content-type", "text/plain")
939 d.addErrback(_check_blocking)
940 def _check_replacement(f):
941 f.trap(NoReplacementError)
942 req.setResponseCode(http.CONFLICT)
943 req.setHeader("content-type", "text/plain")
945 d.addErrback(_check_replacement)
948 def _get_or_create_directories(self, node, path):
949 if not IDirectoryNode.providedBy(node):
950 # unfortunately it is too late to provide the name of the
951 # blocking directory in the error message.
952 raise BlockingFileError("cannot create directory because there "
953 "is a file in the way")
955 return defer.succeed(node)
956 d = node.get(path[0])
957 def _maybe_create(f):
959 return node.create_empty_directory(path[0])
960 d.addErrback(_maybe_create)
961 d.addCallback(self._get_or_create_directories, path[1:])
964 def _check_replacement(self, node, name, replace):
967 d = node.has_child(name)
970 raise NoReplacementError("There was already a child by that "
971 "name, and you asked me to not "
977 def _mkdir(self, node, name):
978 d = node.create_empty_directory(name)
980 return newnode.get_uri()
984 def _upload_file(self, node, contents, name):
985 uploadable = FileHandle(contents)
986 d = node.add_file(name, uploadable)
988 log.msg("webish upload complete")
989 return filenode.get_uri()
993 def _upload_localfile(self, node, localfile, name):
994 uploadable = FileName(localfile)
995 d = node.add_file(name, uploadable)
996 d.addCallback(lambda filenode: filenode.get_uri())
999 def _attach_uri(self, parentnode, contents, name):
1000 newuri = contents.read().strip()
1001 d = parentnode.set_uri(name, newuri)
1004 d.addCallback(_done)
1007 def _upload_localdir(self, node, localdir):
1008 # build up a list of files to upload
1011 msg = "No files to upload! %s is empty" % localdir
1012 if not os.path.exists(localdir):
1013 msg = "%s doesn't exist!" % localdir
1014 for root, dirs, files in os.walk(localdir):
1015 if root == localdir:
1018 relative_root = root[len(localdir)+1:]
1019 path = tuple(relative_root.split(os.sep))
1021 all_dirs.append(path + (d,))
1023 all_files.append(path + (f,))
1024 d = defer.succeed(msg)
1025 for dir in all_dirs:
1027 d.addCallback(self._makedir, node, dir)
1029 d.addCallback(self._upload_one_file, node, localdir, f)
1032 def _makedir(self, res, node, dir):
1033 d = defer.succeed(None)
1034 # get the parent. As long as os.walk gives us parents before
1035 # children, this ought to work
1036 d.addCallback(lambda res: node.get_child_at_path(dir[:-1]))
1037 # then create the child directory
1038 d.addCallback(lambda parent: parent.create_empty_directory(dir[-1]))
1041 def _upload_one_file(self, res, node, localdir, f):
1042 # get the parent. We can be sure this exists because we already
1043 # went through and created all the directories we require.
1044 localfile = os.path.join(localdir, *f)
1045 d = node.get_child_at_path(f[:-1])
1046 d.addCallback(self._upload_localfile, localfile, f[-1])
1050 class Manifest(rend.Page):
1051 docFactory = getxmlfile("manifest.xhtml")
1052 def __init__(self, dirnode, dirpath):
1053 self._dirnode = dirnode
1054 self._dirpath = dirpath
1056 def dirpath_as_string(self):
1057 return "/" + "/".join(self._dirpath)
1059 def render_title(self, ctx):
1060 return T.title["Manifest of %s" % self.dirpath_as_string()]
1062 def render_header(self, ctx):
1063 return T.p["Manifest of %s" % self.dirpath_as_string()]
1065 def data_items(self, ctx, data):
1066 return self._dirnode.build_manifest()
1068 def render_row(self, ctx, refresh_cap):
1069 ctx.fillSlots("refresh_capability", refresh_cap)
1073 implements(inevow.IResource)
1074 def renderHTTP(self, ctx):
1075 req = inevow.IRequest(ctx)
1076 req.setResponseCode(http.BAD_REQUEST)
1077 req.setHeader("content-type", "text/plain")
1080 def child_error(text):
1085 class VDrive(rend.Page):
1087 def __init__(self, node, name):
1091 def get_child_at_path(self, path):
1093 return self.node.get_child_at_path(path)
1094 return defer.succeed(self.node)
1096 def locateChild(self, ctx, segments):
1097 req = inevow.IRequest(ctx)
1101 t = get_arg(req, "t", "")
1102 localfile = get_arg(req, "localfile", None)
1103 if localfile is not None:
1104 if localfile != os.path.abspath(localfile):
1105 return NeedAbsolutePathError(), ()
1106 localdir = get_arg(req, "localdir", None)
1107 if localdir is not None:
1108 if localdir != os.path.abspath(localdir):
1109 return NeedAbsolutePathError(), ()
1110 if localfile or localdir:
1111 if not ILocalAccess(ctx).local_access_is_allowed():
1112 return LocalAccessDisabledError(), ()
1113 if req.getHost().host != LOCALHOST:
1114 return NeedLocalhostError(), ()
1115 # TODO: think about clobbering/revealing config files and node secrets
1117 replace = boolean_of_arg(get_arg(req, "replace", "true"))
1120 # the node must exist, and our operation will be performed on the
1122 d = self.get_child_at_path(path)
1123 def file_or_dir(node):
1124 if (IFileNode.providedBy(node)
1125 or IMutableFileNode.providedBy(node)):
1126 filename = "unknown"
1129 filename = get_arg(req, "filename", filename)
1132 # write contents to a local file
1133 return LocalFileDownloader(node, localfile), ()
1134 # send contents as the result
1135 return FileDownloader(node, filename), ()
1137 # send contents as the result
1138 return FileDownloader(node, filename), ()
1140 return FileJSONMetadata(node), ()
1142 return FileURI(node), ()
1143 elif t == "readonly-uri":
1144 return FileReadOnlyURI(node), ()
1146 return child_error("bad t=%s" % t)
1147 elif IDirectoryNode.providedBy(node):
1150 # recursive download to a local directory
1151 return LocalDirectoryDownloader(node, localdir), ()
1152 return child_error("t=download requires localdir=")
1154 # send an HTML representation of the directory
1155 return Directory(self.name, node, path), ()
1157 return DirectoryJSONMetadata(node), ()
1159 return DirectoryURI(node), ()
1160 elif t == "readonly-uri":
1161 return DirectoryReadonlyURI(node), ()
1162 elif t == "manifest":
1163 return Manifest(node, path), ()
1164 elif t == 'rename-form':
1165 return RenameForm(self.name, node, path), ()
1167 return child_error("bad t=%s" % t)
1169 return child_error("unknown node type")
1170 d.addCallback(file_or_dir)
1171 elif method == "POST":
1172 # the node must exist, and our operation will be performed on the
1174 d = self.get_child_at_path(path)
1175 def _got_POST(node):
1176 return POSTHandler(node, replace), ()
1177 d.addCallback(_got_POST)
1178 elif method == "DELETE":
1179 # the node must exist, and our operation will be performed on its
1181 assert path # you can't delete the root
1182 d = self.get_child_at_path(path[:-1])
1183 def _got_DELETE(node):
1184 return DELETEHandler(node, path[-1]), ()
1185 d.addCallback(_got_DELETE)
1186 elif method in ("PUT",):
1187 # the node may or may not exist, and our operation may involve
1188 # all the ancestors of the node.
1189 return PUTHandler(self.node, path, t, localfile, localdir, replace), ()
1191 return rend.NotFound
1194 class URIPUTHandler(rend.Page):
1195 def renderHTTP(self, ctx):
1196 req = inevow.IRequest(ctx)
1197 assert req.method == "PUT"
1199 t = get_arg(req, "t", "")
1202 # "PUT /uri", to create an unlinked file. This is like PUT but
1203 # without the associated set_uri.
1204 uploadable = FileHandle(req.content)
1205 d = IClient(ctx).upload(uploadable)
1206 # that fires with the URI of the new file
1210 # "PUT /uri?t=mkdir", to create an unlinked directory.
1211 d = IClient(ctx).create_empty_dirnode()
1212 d.addCallback(lambda dirnode: dirnode.get_uri())
1213 # XXX add redirect_to_result
1216 req.setResponseCode(http.BAD_REQUEST)
1217 req.setHeader("content-type", "text/plain")
1218 return "/uri only accepts PUT and PUT?t=mkdir"
1220 class URIPOSTHandler(rend.Page):
1221 def renderHTTP(self, ctx):
1222 req = inevow.IRequest(ctx)
1223 assert req.method == "POST"
1225 t = get_arg(req, "t", "").strip()
1227 if t in ("", "upload"):
1228 # "POST /uri", to create an unlinked file.
1229 fileobj = req.fields["file"].file
1230 uploadable = FileHandle(fileobj)
1231 d = IClient(ctx).upload(uploadable)
1232 # that fires with the URI of the new file
1236 # "POST /uri?t=mkdir", to create an unlinked directory.
1237 d = IClient(ctx).create_empty_dirnode()
1238 redirect = get_arg(req, "redirect_to_result", "false")
1239 if boolean_of_arg(redirect):
1240 def _then_redir(res):
1241 new_url = "uri/" + urllib.quote(res.get_uri())
1242 req.setResponseCode(http.SEE_OTHER) # 303
1243 req.setHeader('location', new_url)
1246 d.addCallback(_then_redir)
1248 d.addCallback(lambda dirnode: dirnode.get_uri())
1251 req.setResponseCode(http.BAD_REQUEST)
1252 req.setHeader("content-type", "text/plain")
1253 err = "/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, and POST?t=mkdir"
1257 class Root(rend.Page):
1260 docFactory = getxmlfile("welcome.xhtml")
1262 def locateChild(self, ctx, segments):
1263 client = IClient(ctx)
1264 req = inevow.IRequest(ctx)
1266 segments = list(segments) # XXX HELP I AM YUCKY!
1267 while segments and not segments[-1]:
1271 segments = tuple(segments)
1273 if segments[0] == "uri":
1274 if len(segments) == 1 or segments[1] == '':
1275 uri = get_arg(req, "uri", None)
1277 there = url.URL.fromContext(ctx)
1278 there = there.clear("uri")
1279 there = there.child("uri").child(uri)
1281 if len(segments) == 1:
1283 if req.method == "PUT":
1284 # either "PUT /uri" to create an unlinked file, or
1285 # "PUT /uri?t=mkdir" to create an unlinked directory
1286 return URIPUTHandler(), ()
1287 elif req.method == "POST":
1288 # "POST /uri?t=upload&file=newfile" to upload an unlinked
1289 # file or "POST /uri?t=mkdir" to create a new directory
1290 return URIPOSTHandler(), ()
1291 if len(segments) < 2:
1292 return rend.NotFound
1294 d = defer.maybeDeferred(client.create_node_from_uri, uri)
1295 d.addCallback(lambda node: VDrive(node, "from-uri"))
1296 d.addCallback(lambda vd: vd.locateChild(ctx, segments[2:]))
1297 def _trap_KeyError(f):
1299 return rend.FourOhFour(), ()
1300 d.addErrback(_trap_KeyError)
1302 elif segments[0] == "xmlrpc":
1303 raise NotImplementedError()
1304 return rend.Page.locateChild(self, ctx, segments)
1306 child_webform_css = webform.defaultCSS
1307 child_tahoe_css = nevow_File(resource_filename('allmydata.web', 'tahoe.css'))
1309 child_provisioning = provisioning.ProvisioningTool()
1311 def data_version(self, ctx, data):
1312 return get_package_versions_string()
1314 def data_my_nodeid(self, ctx, data):
1315 return b32encode(IClient(ctx).nodeid).lower()
1316 def data_introducer_furl(self, ctx, data):
1317 return IClient(ctx).introducer_furl
1318 def data_connected_to_introducer(self, ctx, data):
1319 if IClient(ctx).connected_to_introducer():
1323 def data_helper_furl(self, ctx, data):
1325 uploader = IClient(ctx).getServiceNamed("uploader")
1328 furl, connected = uploader.get_helper_info()
1330 def data_connected_to_helper(self, ctx, data):
1332 uploader = IClient(ctx).getServiceNamed("uploader")
1334 return "no" # we don't even have an Uploader
1335 furl, connected = uploader.get_helper_info()
1340 def data_num_peers(self, ctx, data):
1341 #client = inevow.ISite(ctx)._client
1342 client = IClient(ctx)
1343 return len(list(client.get_all_peerids()))
1345 def data_peers(self, ctx, data):
1347 client = IClient(ctx)
1348 for nodeid in sorted(client.get_all_peerids()):
1349 row = (b32encode(nodeid).lower(),)
1353 def render_row(self, ctx, data):
1355 ctx.fillSlots("peerid", nodeid_a)
1358 # this is a form where users can download files by URI
1359 def render_download_form(self, ctx, data):
1360 form = T.form(action="uri", method="get",
1361 enctype="multipart/form-data")[
1363 T.legend(class_="freeform-form-label")["download a file"],
1364 "URI of file to download: ",
1365 T.input(type="text", name="uri"), " ",
1366 "Filename to download as: ",
1367 T.input(type="text", name="filename"), " ",
1368 T.input(type="submit", value="download"),
1372 # this is a form where users can create new directories
1373 def render_mkdir_form(self, ctx, data):
1374 form = T.form(action="uri", method="post",
1375 enctype="multipart/form-data")[
1377 T.legend(class_="freeform-form-label")["create a directory"],
1378 T.input(type="hidden", name="t", value="mkdir"),
1379 T.input(type="hidden", name="redirect_to_result", value="true"),
1380 T.input(type="submit", value="create"),
1386 implements(ILocalAccess)
1388 self.local_access = False
1389 def local_access_is_allowed(self):
1390 return self.local_access
1392 class WebishServer(service.MultiService):
1395 def __init__(self, webport, nodeurl_path=None):
1396 service.MultiService.__init__(self)
1397 self.webport = webport
1399 self.site = site = appserver.NevowSite(self.root)
1400 self.site.requestFactory = MyRequest
1401 self.allow_local = LocalAccess()
1402 self.site.remember(self.allow_local, ILocalAccess)
1403 s = strports.service(webport, site)
1404 s.setServiceParent(self)
1405 self.listener = s # stash it so the tests can query for the portnum
1406 self._started = defer.Deferred()
1408 self._started.addCallback(self._write_nodeurl_file, nodeurl_path)
1410 def allow_local_access(self, enable=True):
1411 self.allow_local.local_access = enable
1413 def startService(self):
1414 service.MultiService.startService(self)
1415 # to make various services available to render_* methods, we stash a
1416 # reference to the client on the NevowSite. This will be available by
1417 # adapting the 'context' argument to a special marker interface named
1419 self.site.remember(self.parent, IClient)
1420 # I thought you could do the same with an existing interface, but
1421 # apparently 'ISite' does not exist
1422 #self.site._client = self.parent
1423 self._started.callback(None)
1425 def _write_nodeurl_file(self, junk, nodeurl_path):
1426 # what is our webport?
1428 if isinstance(s, internet.TCPServer):
1429 base_url = "http://localhost:%d" % s._port.getHost().port
1430 elif isinstance(s, internet.SSLServer):
1431 base_url = "https://localhost:%d" % s._port.getHost().port
1435 f = open(nodeurl_path, 'wb')
1436 # this file is world-readable
1437 f.write(base_url + "\n")