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 util, 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
24 return loaders.xmlfile(util.sibpath(__file__, "web/%s" % name))
26 class IClient(Interface):
28 class ILocalAccess(Interface):
29 def local_access_is_allowed():
30 """Return True if t=upload&localdir= is allowed, giving anyone who
31 can talk to the webserver control over the local (disk) filesystem."""
33 def boolean_of_arg(arg):
34 assert arg.lower() in ("true", "t", "1", "false", "f", "0")
35 return arg.lower() in ("true", "t", "1")
37 def get_arg(req, argname, default=None, multiple=False):
38 """Extract an argument from either the query args (req.args) or the form
39 body fields (req.fields). If multiple=False, this returns a single value
40 (or the default, which defaults to None), and the query args take
41 precedence. If multiple=True, this returns a tuple of arguments (possibly
42 empty), starting with all those in the query args.
45 if argname in req.args:
46 results.extend(req.args[argname])
47 if req.fields and argname in req.fields:
48 results.append(req.fields[argname].value)
55 # we must override twisted.web.http.Request.requestReceived with a version
56 # that doesn't use cgi.parse_multipart() . Since we actually use Nevow, we
57 # override the nevow-specific subclass, nevow.appserver.NevowRequest . This
58 # is an exact copy of twisted.web.http.Request (from SVN HEAD on 10-Aug-2007)
59 # that modifies the way form arguments are parsed. Note that this sort of
60 # surgery may induce a dependency upon a particular version of twisted.web
62 parse_qs = http.parse_qs
63 class MyRequest(appserver.NevowRequest):
65 def requestReceived(self, command, path, version):
66 """Called by channel when all data has been received.
68 This method is not intended for users.
70 self.content.seek(0,0)
74 self.method, self.uri = command, path
75 self.clientproto = version
76 x = self.uri.split('?', 1)
81 self.path, argstring = x
82 self.args = parse_qs(argstring, 1)
84 # cache the client and server information, we'll need this later to be
85 # serialized and sent with the request so CGIs will work remotely
86 self.client = self.channel.transport.getPeer()
87 self.host = self.channel.transport.getHost()
89 # Argument processing.
91 ## The original twisted.web.http.Request.requestReceived code parsed the
92 ## content and added the form fields it found there to self.args . It
93 ## did this with cgi.parse_multipart, which holds the arguments in RAM
94 ## and is thus unsuitable for large file uploads. The Nevow subclass
95 ## (nevow.appserver.NevowRequest) uses cgi.FieldStorage instead (putting
96 ## the results in self.fields), which is much more memory-efficient.
97 ## Since we know we're using Nevow, we can anticipate these arguments
98 ## appearing in self.fields instead of self.args, and thus skip the
99 ## parse-content-into-self.args step.
102 ## ctype = self.getHeader('content-type')
103 ## if self.method == "POST" and ctype:
104 ## mfd = 'multipart/form-data'
105 ## key, pdict = cgi.parse_header(ctype)
106 ## if key == 'application/x-www-form-urlencoded':
107 ## args.update(parse_qs(self.content.read(), 1))
110 ## args.update(cgi.parse_multipart(self.content, pdict))
111 ## except KeyError, e:
112 ## if e.args[0] == 'content-disposition':
113 ## # Parse_multipart can't cope with missing
114 ## # content-dispostion headers in multipart/form-data
115 ## # parts, so we catch the exception and tell the client
116 ## # it was a bad request.
117 ## self.channel.transport.write(
118 ## "HTTP/1.1 400 Bad Request\r\n\r\n")
119 ## self.channel.transport.loseConnection()
125 class Directory(rend.Page):
127 docFactory = getxmlfile("directory.xhtml")
129 def __init__(self, rootname, dirnode, dirpath):
130 self._rootname = rootname
131 self._dirnode = dirnode
132 self._dirpath = dirpath
134 def dirpath_as_string(self):
135 return "/" + "/".join(self._dirpath)
137 def render_title(self, ctx, data):
138 return ctx.tag["Directory '%s':" % self.dirpath_as_string()]
140 def render_header(self, ctx, data):
141 parent_directories = ("<%s>" % self._rootname,) + self._dirpath
142 num_dirs = len(parent_directories)
144 header = ["Directory '"]
145 for i,d in enumerate(parent_directories):
146 upness = num_dirs - i - 1
148 link = "/".join( ("..",) * upness )
151 header.append(T.a(href=link)[d])
156 if self._dirnode.is_readonly():
157 header.append(" (readonly)")
159 return ctx.tag[header]
161 def render_welcome(self, ctx, data):
162 depth = len(self._dirpath) + 2
163 link = "/".join([".."] * depth)
164 return T.div[T.a(href=link)["Return to Welcome page"]]
166 def data_children(self, ctx, data):
167 d = self._dirnode.list()
168 d.addCallback(lambda dict: sorted(dict.items()))
171 def render_row(self, ctx, data):
172 name, (target, metadata) = data
174 if self._dirnode.is_readonly():
178 # this creates a button which will cause our child__delete method
179 # to be invoked, which deletes the file and then redirects the
180 # browser back to this directory
181 delete = T.form(action=url.here, method="post")[
182 T.input(type='hidden', name='t', value='delete'),
183 T.input(type='hidden', name='name', value=name),
184 T.input(type='hidden', name='when_done', value=url.here),
185 T.input(type='submit', value='del', name="del"),
188 rename = T.form(action=url.here, method="get")[
189 T.input(type='hidden', name='t', value='rename-form'),
190 T.input(type='hidden', name='name', value=name),
191 T.input(type='hidden', name='when_done', value=url.here),
192 T.input(type='submit', value='rename', name="rename"),
195 ctx.fillSlots("delete", delete)
196 ctx.fillSlots("rename", rename)
197 check = T.form(action=url.here, method="post")[
198 T.input(type='hidden', name='t', value='check'),
199 T.input(type='hidden', name='name', value=name),
200 T.input(type='hidden', name='when_done', value=url.here),
201 T.input(type='submit', value='check', name="check"),
203 ctx.fillSlots("overwrite", self.build_overwrite(ctx, (name, target)))
204 ctx.fillSlots("check", check)
206 # build the base of the uri_link link url
207 uri_link = "/uri/" + urllib.quote(target.get_uri())
209 assert (IFileNode.providedBy(target)
210 or IDirectoryNode.providedBy(target)
211 or IMutableFileNode.providedBy(target)), target
213 if IMutableFileNode.providedBy(target):
216 # add the filename to the uri_link url
217 uri_link += '?%s' % (urllib.urlencode({'filename': name}),)
219 # to prevent javascript in displayed .html files from stealing a
220 # secret directory URI from the URL, send the browser to a URI-based
221 # page that doesn't know about the directory at all
222 #dlurl = urllib.quote(name)
225 ctx.fillSlots("filename",
226 T.a(href=dlurl)[html.escape(name)])
227 ctx.fillSlots("type", "SSK")
229 ctx.fillSlots("size", "?")
231 text_plain_link = uri_link + "?filename=foo.txt"
232 text_plain_tag = T.a(href=text_plain_link)["text/plain"]
234 elif IFileNode.providedBy(target):
237 # add the filename to the uri_link url
238 uri_link += '?%s' % (urllib.urlencode({'filename': name}),)
240 # to prevent javascript in displayed .html files from stealing a
241 # secret directory URI from the URL, send the browser to a URI-based
242 # page that doesn't know about the directory at all
243 #dlurl = urllib.quote(name)
246 ctx.fillSlots("filename",
247 T.a(href=dlurl)[html.escape(name)])
248 ctx.fillSlots("type", "FILE")
250 ctx.fillSlots("size", target.get_size())
252 text_plain_link = uri_link + "?filename=foo.txt"
253 text_plain_tag = T.a(href=text_plain_link)["text/plain"]
255 elif IDirectoryNode.providedBy(target):
257 subdir_url = urllib.quote(name)
258 ctx.fillSlots("filename",
259 T.a(href=subdir_url)[html.escape(name)])
260 if target.is_readonly():
264 ctx.fillSlots("type", dirtype)
265 ctx.fillSlots("size", "-")
266 text_plain_tag = None
268 childdata = [T.a(href="%s?t=json" % name)["JSON"], ", ",
269 T.a(href="%s?t=uri" % name)["URI"], ", ",
270 T.a(href="%s?t=readonly-uri" % name)["readonly-URI"], ", ",
271 T.a(href=uri_link)["URI-link"],
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"""
474 LOCALHOST = "127.0.0.1"
476 class NeedLocalhostError:
477 implements(inevow.IResource)
479 def renderHTTP(self, ctx):
480 req = inevow.IRequest(ctx)
481 req.setResponseCode(http.FORBIDDEN)
482 req.setHeader("content-type", "text/plain")
483 return "localfile= or localdir= requires a local connection"
485 class NeedAbsolutePathError:
486 implements(inevow.IResource)
488 def renderHTTP(self, ctx):
489 req = inevow.IRequest(ctx)
490 req.setResponseCode(http.FORBIDDEN)
491 req.setHeader("content-type", "text/plain")
492 return "localfile= or localdir= requires an absolute path"
494 class LocalAccessDisabledError:
495 implements(inevow.IResource)
497 def renderHTTP(self, ctx):
498 req = inevow.IRequest(ctx)
499 req.setResponseCode(http.FORBIDDEN)
500 req.setHeader("content-type", "text/plain")
501 return "local file access is disabled"
504 class LocalFileDownloader(resource.Resource):
505 def __init__(self, filenode, local_filename):
506 self._local_filename = local_filename
508 self._filenode = filenode
510 def render(self, req):
511 target = download.FileName(self._local_filename)
512 d = self._filenode.download(target)
514 req.write(self._filenode.get_uri())
517 return server.NOT_DONE_YET
520 class FileJSONMetadata(rend.Page):
521 def __init__(self, filenode):
522 self._filenode = filenode
524 def renderHTTP(self, ctx):
525 req = inevow.IRequest(ctx)
526 req.setHeader("content-type", "text/plain")
527 return self.renderNode(self._filenode)
529 def renderNode(self, filenode):
530 file_uri = filenode.get_uri()
533 'size': filenode.get_size(),
535 return simplejson.dumps(data, indent=1)
537 class FileURI(FileJSONMetadata):
538 def renderNode(self, filenode):
539 file_uri = filenode.get_uri()
542 class FileReadOnlyURI(FileJSONMetadata):
543 def renderNode(self, filenode):
544 if filenode.is_readonly():
545 return filenode.get_uri()
547 return filenode.get_readonly().get_uri()
549 class DirnodeWalkerMixin:
550 """Visit all nodes underneath (and including) the rootnode, one at a
551 time. For each one, call the visitor. The visitor will see the
552 IDirectoryNode before it sees any of the IFileNodes inside. If the
553 visitor returns a Deferred, I do not call the visitor again until it has
557 ## def _walk_if_we_could_use_generators(self, rootnode, rootpath=()):
558 ## # this is what we'd be doing if we didn't have the Deferreds and
559 ## # thus could use generators
560 ## yield rootpath, rootnode
561 ## for childname, childnode in rootnode.list().items():
562 ## childpath = rootpath + (childname,)
563 ## if IFileNode.providedBy(childnode):
564 ## yield childpath, childnode
565 ## elif IDirectoryNode.providedBy(childnode):
566 ## for res in self._walk_if_we_could_use_generators(childnode,
570 def walk(self, rootnode, visitor, rootpath=()):
572 def _listed(listing):
573 return listing.items()
574 d.addCallback(_listed)
575 d.addCallback(self._handle_items, visitor, rootpath)
578 def _handle_items(self, items, visitor, rootpath):
581 childname, (childnode, metadata) = items[0]
582 childpath = rootpath + (childname,)
583 d = defer.maybeDeferred(visitor, childpath, childnode, metadata)
584 if IDirectoryNode.providedBy(childnode):
585 d.addCallback(lambda res: self.walk(childnode, visitor, childpath))
586 d.addCallback(lambda res:
587 self._handle_items(items[1:], visitor, rootpath))
590 class LocalDirectoryDownloader(resource.Resource, DirnodeWalkerMixin):
591 def __init__(self, dirnode, localdir):
592 self._dirnode = dirnode
593 self._localdir = localdir
595 def _handle(self, path, node, metadata):
596 localfile = os.path.join(self._localdir, os.sep.join(path))
597 if IDirectoryNode.providedBy(node):
598 fileutil.make_dirs(localfile)
599 elif IFileNode.providedBy(node):
600 target = download.FileName(localfile)
601 return node.download(target)
603 def render(self, req):
604 d = self.walk(self._dirnode, self._handle)
606 req.setHeader("content-type", "text/plain")
607 return "operation complete"
611 class DirectoryJSONMetadata(rend.Page):
612 def __init__(self, dirnode):
613 self._dirnode = dirnode
615 def renderHTTP(self, ctx):
616 req = inevow.IRequest(ctx)
617 req.setHeader("content-type", "text/plain")
618 return self.renderNode(self._dirnode)
620 def renderNode(self, node):
624 for name, (childnode, metadata) in children.iteritems():
625 if IFileNode.providedBy(childnode):
626 kiduri = childnode.get_uri()
627 kiddata = ("filenode",
629 'size': childnode.get_size(),
632 assert IDirectoryNode.providedBy(childnode), (childnode, children,)
633 kiddata = ("dirnode",
634 {'ro_uri': childnode.get_readonly_uri(),
636 if not childnode.is_readonly():
637 kiddata[1]['rw_uri'] = childnode.get_uri()
639 contents = { 'children': kids,
640 'ro_uri': node.get_readonly_uri(),
642 if not node.is_readonly():
643 contents['rw_uri'] = node.get_uri()
644 data = ("dirnode", contents)
645 return simplejson.dumps(data, indent=1)
649 class DirectoryURI(DirectoryJSONMetadata):
650 def renderNode(self, node):
651 return node.get_uri()
653 class DirectoryReadonlyURI(DirectoryJSONMetadata):
654 def renderNode(self, node):
655 return node.get_readonly_uri()
657 class RenameForm(rend.Page):
659 docFactory = getxmlfile("rename-form.xhtml")
661 def __init__(self, rootname, dirnode, dirpath):
662 self._rootname = rootname
663 self._dirnode = dirnode
664 self._dirpath = dirpath
666 def dirpath_as_string(self):
667 return "/" + "/".join(self._dirpath)
669 def render_title(self, ctx, data):
670 return ctx.tag["Directory '%s':" % self.dirpath_as_string()]
672 def render_header(self, ctx, data):
673 parent_directories = ("<%s>" % self._rootname,) + self._dirpath
674 num_dirs = len(parent_directories)
676 header = [ "Rename in directory '",
677 "<%s>/" % self._rootname,
678 "/".join(self._dirpath),
681 if self._dirnode.is_readonly():
682 header.append(" (readonly)")
683 return ctx.tag[header]
685 def render_when_done(self, ctx, data):
686 return T.input(type="hidden", name="when_done", value=url.here)
688 def render_get_name(self, ctx, data):
689 req = inevow.IRequest(ctx)
690 name = get_arg(req, "name", "")
691 ctx.tag.attributes['value'] = name
694 class POSTHandler(rend.Page):
695 def __init__(self, node, replace):
697 self._replace = replace
699 def _check_replacement(self, name):
701 return defer.succeed(None)
702 d = self._node.has_child(name)
705 raise NoReplacementError("There was already a child by that "
706 "name, and you asked me to not "
712 def renderHTTP(self, ctx):
713 req = inevow.IRequest(ctx)
715 t = get_arg(req, "t")
718 name = get_arg(req, "name", None)
719 if name and "/" in name:
720 req.setResponseCode(http.BAD_REQUEST)
721 req.setHeader("content-type", "text/plain")
722 return "name= may not contain a slash"
725 # we allow the user to delete an empty-named file, but not to create
726 # them, since that's an easy and confusing mistake to make
728 when_done = get_arg(req, "when_done", None)
729 if not boolean_of_arg(get_arg(req, "replace", "true")):
730 self._replace = False
734 raise RuntimeError("mkdir requires a name")
735 d = self._check_replacement(name)
736 d.addCallback(lambda res: self._node.create_empty_directory(name))
737 d.addCallback(lambda res: "directory created")
740 raise RuntimeError("set-uri requires a name")
741 newuri = get_arg(req, "uri")
742 assert newuri is not None
743 d = self._check_replacement(name)
744 d.addCallback(lambda res: self._node.set_uri(name, newuri))
745 d.addCallback(lambda res: newuri)
748 # apparently an <input type="hidden" name="name" value="">
749 # won't show up in the resulting encoded form.. the 'name'
750 # field is completely missing. So to allow deletion of an
751 # empty file, we have to pretend that None means ''. The only
752 # downide of this is a slightly confusing error message if
753 # someone does a POST without a name= field. For our own HTML
754 # thisn't a big deal, because we create the 'delete' POST
757 d = self._node.delete(name)
758 d.addCallback(lambda res: "thing deleted")
760 from_name = 'from_name' in req.fields and req.fields["from_name"].value
761 if from_name is not None:
762 from_name = from_name.strip()
763 to_name = 'to_name' in req.fields and req.fields["to_name"].value
764 if to_name is not None:
765 to_name = to_name.strip()
766 if not from_name or not to_name:
767 raise RuntimeError("rename requires from_name and to_name")
768 if not IDirectoryNode.providedBy(self._node):
769 raise RuntimeError("rename must only be called on directories")
770 for k,v in [ ('from_name', from_name), ('to_name', to_name) ]:
772 req.setResponseCode(http.BAD_REQUEST)
773 req.setHeader("content-type", "text/plain")
774 return "%s= may not contain a slash" % (k,)
775 d = self._check_replacement(to_name)
776 d.addCallback(lambda res: self._node.get(from_name))
778 uri = child.get_uri()
779 # now actually do the rename
780 return self._node.set_uri(to_name, uri)
781 d.addCallback(add_dest)
783 return self._node.delete(from_name)
784 d.addCallback(rm_src)
785 d.addCallback(lambda res: "thing renamed")
788 if "mutable" in req.fields:
789 contents = req.fields["file"]
790 name = name or contents.filename
794 raise RuntimeError("upload-mutable requires a name")
795 # SDMF: files are small, and we can only upload data.
796 contents.file.seek(0)
797 data = contents.file.read()
798 uploadable = FileHandle(contents.file)
799 d = self._check_replacement(name)
800 d.addCallback(lambda res: self._node.has_child(name))
801 def _checked(present):
803 # modify the existing one instead of creating a new
805 d2 = self._node.get(name)
806 def _got_newnode(newnode):
807 d3 = newnode.replace(data)
808 d3.addCallback(lambda res: newnode.get_uri())
810 d2.addCallback(_got_newnode)
812 d2 = IClient(ctx).create_mutable_file(data)
813 def _uploaded(newnode):
814 d1 = self._node.set_node(name, newnode)
815 d1.addCallback(lambda res: newnode.get_uri())
817 d2.addCallback(_uploaded)
819 d.addCallback(_checked)
821 contents = req.fields["file"]
822 name = name or contents.filename
826 raise RuntimeError("upload requires a name")
827 uploadable = FileHandle(contents.file)
828 d = self._check_replacement(name)
829 d.addCallback(lambda res: self._node.add_file(name, uploadable))
831 return newnode.get_uri()
834 elif t == "overwrite":
835 contents = req.fields["file"]
836 # SDMF: files are small, and we can only upload data.
837 contents.file.seek(0)
838 data = contents.file.read()
839 # TODO: 'name' handling needs review
840 d = defer.succeed(self._node)
841 def _got_child_overwrite(child_node):
842 child_node.replace(data)
843 return child_node.get_uri()
844 d.addCallback(_got_child_overwrite)
847 d = self._node.get(name)
848 def _got_child_check(child_node):
849 d2 = child_node.check()
851 log.msg("checked %s, results %s" % (child_node, res))
853 d2.addCallback(_done)
855 d.addCallback(_got_child_check)
858 return "BAD t=%s" % t
860 d.addCallback(lambda res: url.URL.fromString(when_done))
861 def _check_replacement(f):
862 # TODO: make this more human-friendly: maybe send them to the
863 # when_done page but with an extra query-arg that will display
864 # the error message in a big box at the top of the page. The
865 # directory page that when_done= usually points to accepts a
866 # result= argument.. use that.
867 f.trap(NoReplacementError)
868 req.setResponseCode(http.CONFLICT)
869 req.setHeader("content-type", "text/plain")
871 d.addErrback(_check_replacement)
874 class DELETEHandler(rend.Page):
875 def __init__(self, node, name):
879 def renderHTTP(self, ctx):
880 req = inevow.IRequest(ctx)
881 d = self._node.delete(self._name)
883 # what should this return??
884 return "%s deleted" % self._name
886 def _trap_missing(f):
888 req.setResponseCode(http.NOT_FOUND)
889 req.setHeader("content-type", "text/plain")
890 return "no such child %s" % self._name
891 d.addErrback(_trap_missing)
894 class PUTHandler(rend.Page):
895 def __init__(self, node, path, t, localfile, localdir, replace):
899 self._localfile = localfile
900 self._localdir = localdir
901 self._replace = replace
903 def renderHTTP(self, ctx):
904 req = inevow.IRequest(ctx)
906 localfile = self._localfile
907 localdir = self._localdir
909 if t == "upload" and not (localfile or localdir):
910 req.setResponseCode(http.BAD_REQUEST)
911 req.setHeader("content-type", "text/plain")
912 return "t=upload requires localfile= or localdir="
914 # we must traverse the path, creating new directories as necessary
915 d = self._get_or_create_directories(self._node, self._path[:-1])
916 name = self._path[-1]
917 d.addCallback(self._check_replacement, name, self._replace)
920 d.addCallback(self._upload_localfile, localfile, name)
924 d.addCallback(self._get_or_create_directories, self._path[-1:])
925 d.addCallback(self._upload_localdir, localdir)
927 d.addCallback(self._attach_uri, req.content, name)
929 d.addCallback(self._mkdir, name)
931 d.addCallback(self._upload_file, req.content, name)
932 def _check_blocking(f):
933 f.trap(BlockingFileError)
934 req.setResponseCode(http.BAD_REQUEST)
935 req.setHeader("content-type", "text/plain")
937 d.addErrback(_check_blocking)
938 def _check_replacement(f):
939 f.trap(NoReplacementError)
940 req.setResponseCode(http.CONFLICT)
941 req.setHeader("content-type", "text/plain")
943 d.addErrback(_check_replacement)
946 def _get_or_create_directories(self, node, path):
947 if not IDirectoryNode.providedBy(node):
948 # unfortunately it is too late to provide the name of the
949 # blocking directory in the error message.
950 raise BlockingFileError("cannot create directory because there "
951 "is a file in the way")
953 return defer.succeed(node)
954 d = node.get(path[0])
955 def _maybe_create(f):
957 return node.create_empty_directory(path[0])
958 d.addErrback(_maybe_create)
959 d.addCallback(self._get_or_create_directories, path[1:])
962 def _check_replacement(self, node, name, replace):
965 d = node.has_child(name)
968 raise NoReplacementError("There was already a child by that "
969 "name, and you asked me to not "
975 def _mkdir(self, node, name):
976 d = node.create_empty_directory(name)
978 return newnode.get_uri()
982 def _upload_file(self, node, contents, name):
983 uploadable = FileHandle(contents)
984 d = node.add_file(name, uploadable)
986 log.msg("webish upload complete")
987 return filenode.get_uri()
991 def _upload_localfile(self, node, localfile, name):
992 uploadable = FileName(localfile)
993 d = node.add_file(name, uploadable)
994 d.addCallback(lambda filenode: filenode.get_uri())
997 def _attach_uri(self, parentnode, contents, name):
998 newuri = contents.read().strip()
999 d = parentnode.set_uri(name, newuri)
1002 d.addCallback(_done)
1005 def _upload_localdir(self, node, localdir):
1006 # build up a list of files to upload
1009 msg = "No files to upload! %s is empty" % localdir
1010 if not os.path.exists(localdir):
1011 msg = "%s doesn't exist!" % localdir
1012 for root, dirs, files in os.walk(localdir):
1013 if root == localdir:
1016 relative_root = root[len(localdir)+1:]
1017 path = tuple(relative_root.split(os.sep))
1019 all_dirs.append(path + (d,))
1021 all_files.append(path + (f,))
1022 d = defer.succeed(msg)
1023 for dir in all_dirs:
1025 d.addCallback(self._makedir, node, dir)
1027 d.addCallback(self._upload_one_file, node, localdir, f)
1030 def _makedir(self, res, node, dir):
1031 d = defer.succeed(None)
1032 # get the parent. As long as os.walk gives us parents before
1033 # children, this ought to work
1034 d.addCallback(lambda res: node.get_child_at_path(dir[:-1]))
1035 # then create the child directory
1036 d.addCallback(lambda parent: parent.create_empty_directory(dir[-1]))
1039 def _upload_one_file(self, res, node, localdir, f):
1040 # get the parent. We can be sure this exists because we already
1041 # went through and created all the directories we require.
1042 localfile = os.path.join(localdir, *f)
1043 d = node.get_child_at_path(f[:-1])
1044 d.addCallback(self._upload_localfile, localfile, f[-1])
1048 class Manifest(rend.Page):
1049 docFactory = getxmlfile("manifest.xhtml")
1050 def __init__(self, dirnode, dirpath):
1051 self._dirnode = dirnode
1052 self._dirpath = dirpath
1054 def dirpath_as_string(self):
1055 return "/" + "/".join(self._dirpath)
1057 def render_title(self, ctx):
1058 return T.title["Manifest of %s" % self.dirpath_as_string()]
1060 def render_header(self, ctx):
1061 return T.p["Manifest of %s" % self.dirpath_as_string()]
1063 def data_items(self, ctx, data):
1064 return self._dirnode.build_manifest()
1066 def render_row(self, ctx, refresh_cap):
1067 ctx.fillSlots("refresh_capability", refresh_cap)
1071 implements(inevow.IResource)
1072 def renderHTTP(self, ctx):
1073 req = inevow.IRequest(ctx)
1074 req.setResponseCode(http.BAD_REQUEST)
1075 req.setHeader("content-type", "text/plain")
1078 def child_error(text):
1083 class VDrive(rend.Page):
1085 def __init__(self, node, name):
1089 def get_child_at_path(self, path):
1091 return self.node.get_child_at_path(path)
1092 return defer.succeed(self.node)
1094 def locateChild(self, ctx, segments):
1095 req = inevow.IRequest(ctx)
1099 t = get_arg(req, "t", "")
1100 localfile = get_arg(req, "localfile", None)
1101 if localfile is not None:
1102 if localfile != os.path.abspath(localfile):
1103 return NeedAbsolutePathError(), ()
1104 localdir = get_arg(req, "localdir", None)
1105 if localdir is not None:
1106 if localdir != os.path.abspath(localdir):
1107 return NeedAbsolutePathError(), ()
1108 if localfile or localdir:
1109 if not ILocalAccess(ctx).local_access_is_allowed():
1110 return LocalAccessDisabledError(), ()
1111 if req.getHost().host != LOCALHOST:
1112 return NeedLocalhostError(), ()
1113 # TODO: think about clobbering/revealing config files and node secrets
1115 replace = boolean_of_arg(get_arg(req, "replace", "true"))
1118 # the node must exist, and our operation will be performed on the
1120 d = self.get_child_at_path(path)
1121 def file_or_dir(node):
1122 if (IFileNode.providedBy(node)
1123 or IMutableFileNode.providedBy(node)):
1124 filename = "unknown"
1127 filename = get_arg(req, "filename", filename)
1130 # write contents to a local file
1131 return LocalFileDownloader(node, localfile), ()
1132 # send contents as the result
1133 return FileDownloader(node, filename), ()
1135 # send contents as the result
1136 return FileDownloader(node, filename), ()
1138 return FileJSONMetadata(node), ()
1140 return FileURI(node), ()
1141 elif t == "readonly-uri":
1142 return FileReadOnlyURI(node), ()
1144 return child_error("bad t=%s" % t)
1145 elif IDirectoryNode.providedBy(node):
1148 # recursive download to a local directory
1149 return LocalDirectoryDownloader(node, localdir), ()
1150 return child_error("t=download requires localdir=")
1152 # send an HTML representation of the directory
1153 return Directory(self.name, node, path), ()
1155 return DirectoryJSONMetadata(node), ()
1157 return DirectoryURI(node), ()
1158 elif t == "readonly-uri":
1159 return DirectoryReadonlyURI(node), ()
1160 elif t == "manifest":
1161 return Manifest(node, path), ()
1162 elif t == 'rename-form':
1163 return RenameForm(self.name, node, path), ()
1165 return child_error("bad t=%s" % t)
1167 return child_error("unknown node type")
1168 d.addCallback(file_or_dir)
1169 elif method == "POST":
1170 # the node must exist, and our operation will be performed on the
1172 d = self.get_child_at_path(path)
1173 def _got_POST(node):
1174 return POSTHandler(node, replace), ()
1175 d.addCallback(_got_POST)
1176 elif method == "DELETE":
1177 # the node must exist, and our operation will be performed on its
1179 assert path # you can't delete the root
1180 d = self.get_child_at_path(path[:-1])
1181 def _got_DELETE(node):
1182 return DELETEHandler(node, path[-1]), ()
1183 d.addCallback(_got_DELETE)
1184 elif method in ("PUT",):
1185 # the node may or may not exist, and our operation may involve
1186 # all the ancestors of the node.
1187 return PUTHandler(self.node, path, t, localfile, localdir, replace), ()
1189 return rend.NotFound
1192 class URIPUTHandler(rend.Page):
1193 def renderHTTP(self, ctx):
1194 req = inevow.IRequest(ctx)
1195 assert req.method == "PUT"
1197 t = get_arg(req, "t", "")
1200 # "PUT /uri", to create an unlinked file. This is like PUT but
1201 # without the associated set_uri.
1202 uploadable = FileHandle(req.content)
1203 d = IClient(ctx).upload(uploadable)
1204 # that fires with the URI of the new file
1208 # "PUT /uri?t=mkdir", to create an unlinked directory.
1209 d = IClient(ctx).create_empty_dirnode()
1210 d.addCallback(lambda dirnode: dirnode.get_uri())
1211 # XXX add redirect_to_result
1214 req.setResponseCode(http.BAD_REQUEST)
1215 req.setHeader("content-type", "text/plain")
1216 return "/uri only accepts PUT and PUT?t=mkdir"
1218 class URIPOSTHandler(rend.Page):
1219 def renderHTTP(self, ctx):
1220 req = inevow.IRequest(ctx)
1221 assert req.method == "POST"
1223 t = get_arg(req, "t", "").strip()
1225 if t in ("", "upload"):
1226 # "POST /uri", to create an unlinked file.
1227 fileobj = req.fields["file"].file
1228 uploadable = FileHandle(fileobj)
1229 d = IClient(ctx).upload(uploadable)
1230 # that fires with the URI of the new file
1234 # "POST /uri?t=mkdir", to create an unlinked directory.
1235 d = IClient(ctx).create_empty_dirnode()
1236 redirect = get_arg(req, "redirect_to_result", "false")
1237 if boolean_of_arg(redirect):
1238 def _then_redir(res):
1239 new_url = "uri/" + urllib.quote(res.get_uri())
1240 req.setResponseCode(http.SEE_OTHER) # 303
1241 req.setHeader('location', new_url)
1244 d.addCallback(_then_redir)
1246 d.addCallback(lambda dirnode: dirnode.get_uri())
1249 req.setResponseCode(http.BAD_REQUEST)
1250 req.setHeader("content-type", "text/plain")
1251 err = "/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, and POST?t=mkdir"
1255 class Root(rend.Page):
1258 docFactory = getxmlfile("welcome.xhtml")
1260 def locateChild(self, ctx, segments):
1261 client = IClient(ctx)
1262 req = inevow.IRequest(ctx)
1264 segments = list(segments) # XXX HELP I AM YUCKY!
1265 while segments and not segments[-1]:
1269 segments = tuple(segments)
1271 if segments[0] == "uri":
1272 if len(segments) == 1 or segments[1] == '':
1273 uri = get_arg(req, "uri", None)
1275 there = url.URL.fromContext(ctx)
1276 there = there.clear("uri")
1277 there = there.child("uri").child(uri)
1279 if len(segments) == 1:
1281 if req.method == "PUT":
1282 # either "PUT /uri" to create an unlinked file, or
1283 # "PUT /uri?t=mkdir" to create an unlinked directory
1284 return URIPUTHandler(), ()
1285 elif req.method == "POST":
1286 # "POST /uri?t=upload&file=newfile" to upload an unlinked
1287 # file or "POST /uri?t=mkdir" to create a new directory
1288 return URIPOSTHandler(), ()
1289 if len(segments) < 2:
1290 return rend.NotFound
1292 d = defer.maybeDeferred(client.create_node_from_uri, uri)
1293 d.addCallback(lambda node: VDrive(node, "from-uri"))
1294 d.addCallback(lambda vd: vd.locateChild(ctx, segments[2:]))
1295 def _trap_KeyError(f):
1297 return rend.FourOhFour(), ()
1298 d.addErrback(_trap_KeyError)
1300 elif segments[0] == "xmlrpc":
1301 raise NotImplementedError()
1302 return rend.Page.locateChild(self, ctx, segments)
1304 child_webform_css = webform.defaultCSS
1305 child_tahoe_css = nevow_File(util.sibpath(__file__, "web/tahoe.css"))
1307 child_provisioning = provisioning.ProvisioningTool()
1309 def data_version(self, ctx, data):
1310 return get_package_versions_string()
1312 def data_my_nodeid(self, ctx, data):
1313 return b32encode(IClient(ctx).nodeid).lower()
1314 def data_introducer_furl(self, ctx, data):
1315 return IClient(ctx).introducer_furl
1316 def data_connected_to_introducer(self, ctx, data):
1317 if IClient(ctx).connected_to_introducer():
1320 def data_num_peers(self, ctx, data):
1321 #client = inevow.ISite(ctx)._client
1322 client = IClient(ctx)
1323 return len(list(client.get_all_peerids()))
1325 def data_peers(self, ctx, data):
1327 client = IClient(ctx)
1328 for nodeid in sorted(client.get_all_peerids()):
1329 row = (b32encode(nodeid).lower(),)
1333 def render_row(self, ctx, data):
1335 ctx.fillSlots("peerid", nodeid_a)
1338 # this is a form where users can download files by URI
1339 def render_download_form(self, ctx, data):
1340 form = T.form(action="uri", method="get",
1341 enctype="multipart/form-data")[
1343 T.legend(class_="freeform-form-label")["download a file"],
1344 "URI of file to download: ",
1345 T.input(type="text", name="uri"), " ",
1346 "Filename to download as: ",
1347 T.input(type="text", name="filename"), " ",
1348 T.input(type="submit", value="download"),
1352 # this is a form where users can create new directories
1353 def render_mkdir_form(self, ctx, data):
1354 form = T.form(action="uri", method="post",
1355 enctype="multipart/form-data")[
1357 T.legend(class_="freeform-form-label")["create a directory"],
1358 T.input(type="hidden", name="t", value="mkdir"),
1359 T.input(type="hidden", name="redirect_to_result", value="true"),
1360 T.input(type="submit", value="create"),
1366 implements(ILocalAccess)
1368 self.local_access = False
1369 def local_access_is_allowed(self):
1370 return self.local_access
1372 class WebishServer(service.MultiService):
1375 def __init__(self, webport, nodeurl_path=None):
1376 service.MultiService.__init__(self)
1377 self.webport = webport
1379 self.site = site = appserver.NevowSite(self.root)
1380 self.site.requestFactory = MyRequest
1381 self.allow_local = LocalAccess()
1382 self.site.remember(self.allow_local, ILocalAccess)
1383 s = strports.service(webport, site)
1384 s.setServiceParent(self)
1385 self.listener = s # stash it so the tests can query for the portnum
1386 self._started = defer.Deferred()
1388 self._started.addCallback(self._write_nodeurl_file, nodeurl_path)
1390 def allow_local_access(self, enable=True):
1391 self.allow_local.local_access = enable
1393 def startService(self):
1394 service.MultiService.startService(self)
1395 # to make various services available to render_* methods, we stash a
1396 # reference to the client on the NevowSite. This will be available by
1397 # adapting the 'context' argument to a special marker interface named
1399 self.site.remember(self.parent, IClient)
1400 # I thought you could do the same with an existing interface, but
1401 # apparently 'ISite' does not exist
1402 #self.site._client = self.parent
1403 self._started.callback(None)
1405 def _write_nodeurl_file(self, junk, nodeurl_path):
1406 # what is our webport?
1408 if isinstance(s, internet.TCPServer):
1409 base_url = "http://localhost:%d" % s._port.getHost().port
1410 elif isinstance(s, internet.SSLServer):
1411 base_url = "https://localhost:%d" % s._port.getHost().port
1415 f = open(nodeurl_path, 'wb')
1416 # this file is world-readable
1417 f.write(base_url + "\n")