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 # we must traverse the path, creating new directories as necessary
910 d = self._get_or_create_directories(self._node, self._path[:-1])
911 name = self._path[-1]
912 d.addCallback(self._check_replacement, name, self._replace)
915 d.addCallback(self._upload_localfile, localfile, name)
918 d.addCallback(self._get_or_create_directories, self._path[-1:])
919 d.addCallback(self._upload_localdir, localdir)
921 raise RuntimeError("t=upload requires localfile= or localdir=")
923 d.addCallback(self._attach_uri, req.content, name)
925 d.addCallback(self._mkdir, name)
927 d.addCallback(self._upload_file, req.content, name)
928 def _check_blocking(f):
929 f.trap(BlockingFileError)
930 req.setResponseCode(http.BAD_REQUEST)
931 req.setHeader("content-type", "text/plain")
933 d.addErrback(_check_blocking)
934 def _check_replacement(f):
935 f.trap(NoReplacementError)
936 req.setResponseCode(http.CONFLICT)
937 req.setHeader("content-type", "text/plain")
939 d.addErrback(_check_replacement)
942 def _get_or_create_directories(self, node, path):
943 if not IDirectoryNode.providedBy(node):
944 # unfortunately it is too late to provide the name of the
945 # blocking directory in the error message.
946 raise BlockingFileError("cannot create directory because there "
947 "is a file in the way")
949 return defer.succeed(node)
950 d = node.get(path[0])
951 def _maybe_create(f):
953 return node.create_empty_directory(path[0])
954 d.addErrback(_maybe_create)
955 d.addCallback(self._get_or_create_directories, path[1:])
958 def _check_replacement(self, node, name, replace):
961 d = node.has_child(name)
964 raise NoReplacementError("There was already a child by that "
965 "name, and you asked me to not "
971 def _mkdir(self, node, name):
972 d = node.create_empty_directory(name)
974 return newnode.get_uri()
978 def _upload_file(self, node, contents, name):
979 uploadable = FileHandle(contents)
980 d = node.add_file(name, uploadable)
982 log.msg("webish upload complete")
983 return filenode.get_uri()
987 def _upload_localfile(self, node, localfile, name):
988 uploadable = FileName(localfile)
989 d = node.add_file(name, uploadable)
990 d.addCallback(lambda filenode: filenode.get_uri())
993 def _attach_uri(self, parentnode, contents, name):
994 newuri = contents.read().strip()
995 d = parentnode.set_uri(name, newuri)
1001 def _upload_localdir(self, node, localdir):
1002 # build up a list of files to upload
1005 msg = "No files to upload! %s is empty" % localdir
1006 if not os.path.exists(localdir):
1007 msg = "%s doesn't exist!" % localdir
1008 for root, dirs, files in os.walk(localdir):
1009 if root == localdir:
1012 relative_root = root[len(localdir)+1:]
1013 path = tuple(relative_root.split(os.sep))
1015 all_dirs.append(path + (d,))
1017 all_files.append(path + (f,))
1018 d = defer.succeed(msg)
1019 for dir in all_dirs:
1021 d.addCallback(self._makedir, node, dir)
1023 d.addCallback(self._upload_one_file, node, localdir, f)
1026 def _makedir(self, res, node, dir):
1027 d = defer.succeed(None)
1028 # get the parent. As long as os.walk gives us parents before
1029 # children, this ought to work
1030 d.addCallback(lambda res: node.get_child_at_path(dir[:-1]))
1031 # then create the child directory
1032 d.addCallback(lambda parent: parent.create_empty_directory(dir[-1]))
1035 def _upload_one_file(self, res, node, localdir, f):
1036 # get the parent. We can be sure this exists because we already
1037 # went through and created all the directories we require.
1038 localfile = os.path.join(localdir, *f)
1039 d = node.get_child_at_path(f[:-1])
1040 d.addCallback(self._upload_localfile, localfile, f[-1])
1044 class Manifest(rend.Page):
1045 docFactory = getxmlfile("manifest.xhtml")
1046 def __init__(self, dirnode, dirpath):
1047 self._dirnode = dirnode
1048 self._dirpath = dirpath
1050 def dirpath_as_string(self):
1051 return "/" + "/".join(self._dirpath)
1053 def render_title(self, ctx):
1054 return T.title["Manifest of %s" % self.dirpath_as_string()]
1056 def render_header(self, ctx):
1057 return T.p["Manifest of %s" % self.dirpath_as_string()]
1059 def data_items(self, ctx, data):
1060 return self._dirnode.build_manifest()
1062 def render_row(self, ctx, refresh_cap):
1063 ctx.fillSlots("refresh_capability", refresh_cap)
1066 class VDrive(rend.Page):
1068 def __init__(self, node, name):
1072 def get_child_at_path(self, path):
1074 return self.node.get_child_at_path(path)
1075 return defer.succeed(self.node)
1077 def locateChild(self, ctx, segments):
1078 req = inevow.IRequest(ctx)
1082 # when we're pointing at a directory (like /uri/$DIR_URI/my_pix),
1083 # Directory.addSlash causes a redirect to /uri/$DIR_URI/my_pix/,
1084 # which appears here as ['my_pix', '']. This is supposed to hit the
1085 # same Directory as ['my_pix'].
1086 if path and path[-1] == '':
1089 t = get_arg(req, "t", "")
1090 localfile = get_arg(req, "localfile", None)
1091 if localfile is not None:
1092 if localfile != os.path.abspath(localfile):
1093 return NeedAbsolutePathError(), ()
1094 localdir = get_arg(req, "localdir", None)
1095 if localdir is not None:
1096 if localdir != os.path.abspath(localdir):
1097 return NeedAbsolutePathError(), ()
1098 if localfile or localdir:
1099 if not ILocalAccess(ctx).local_access_is_allowed():
1100 return LocalAccessDisabledError(), ()
1101 if req.getHost().host != LOCALHOST:
1102 return NeedLocalhostError(), ()
1103 # TODO: think about clobbering/revealing config files and node secrets
1105 replace = boolean_of_arg(get_arg(req, "replace", "true"))
1108 # the node must exist, and our operation will be performed on the
1110 d = self.get_child_at_path(path)
1111 def file_or_dir(node):
1112 if (IFileNode.providedBy(node)
1113 or IMutableFileNode.providedBy(node)):
1114 filename = "unknown"
1117 filename = get_arg(req, "filename", filename)
1120 # write contents to a local file
1121 return LocalFileDownloader(node, localfile), ()
1122 # send contents as the result
1123 return FileDownloader(node, filename), ()
1125 # send contents as the result
1126 return FileDownloader(node, filename), ()
1128 return FileJSONMetadata(node), ()
1130 return FileURI(node), ()
1131 elif t == "readonly-uri":
1132 return FileReadOnlyURI(node), ()
1134 raise RuntimeError("bad t=%s" % t)
1135 elif IDirectoryNode.providedBy(node):
1138 # recursive download to a local directory
1139 return LocalDirectoryDownloader(node, localdir), ()
1140 raise RuntimeError("t=download requires localdir=")
1142 # send an HTML representation of the directory
1143 return Directory(self.name, node, path), ()
1145 return DirectoryJSONMetadata(node), ()
1147 return DirectoryURI(node), ()
1148 elif t == "readonly-uri":
1149 return DirectoryReadonlyURI(node), ()
1150 elif t == "manifest":
1151 return Manifest(node, path), ()
1152 elif t == 'rename-form':
1153 return RenameForm(self.name, node, path), ()
1155 raise RuntimeError("bad t=%s" % t)
1157 raise RuntimeError("unknown node type")
1158 d.addCallback(file_or_dir)
1159 elif method == "POST":
1160 # the node must exist, and our operation will be performed on the
1162 d = self.get_child_at_path(path)
1163 def _got_POST(node):
1164 return POSTHandler(node, replace), ()
1165 d.addCallback(_got_POST)
1166 elif method == "DELETE":
1167 # the node must exist, and our operation will be performed on its
1169 assert path # you can't delete the root
1170 d = self.get_child_at_path(path[:-1])
1171 def _got_DELETE(node):
1172 return DELETEHandler(node, path[-1]), ()
1173 d.addCallback(_got_DELETE)
1174 elif method in ("PUT",):
1175 # the node may or may not exist, and our operation may involve
1176 # all the ancestors of the node.
1177 return PUTHandler(self.node, path, t, localfile, localdir, replace), ()
1179 return rend.NotFound
1180 def _trap_KeyError(f):
1182 return rend.FourOhFour(), ()
1183 d.addErrback(_trap_KeyError)
1186 class URIPUTHandler(rend.Page):
1187 def renderHTTP(self, ctx):
1188 req = inevow.IRequest(ctx)
1189 assert req.method == "PUT"
1191 t = get_arg(req, "t", "")
1194 # "PUT /uri", to create an unlinked file. This is like PUT but
1195 # without the associated set_uri.
1196 uploadable = FileHandle(req.content)
1197 d = IClient(ctx).upload(uploadable)
1198 # that fires with the URI of the new file
1202 # "PUT /uri?t=mkdir", to create an unlinked directory.
1203 d = IClient(ctx).create_empty_dirnode()
1204 d.addCallback(lambda dirnode: dirnode.get_uri())
1205 # XXX add redirect_to_result
1208 req.setResponseCode(http.BAD_REQUEST)
1209 req.setHeader("content-type", "text/plain")
1210 return "/uri only accepts PUT and PUT?t=mkdir"
1212 class URIPOSTHandler(rend.Page):
1213 def renderHTTP(self, ctx):
1214 req = inevow.IRequest(ctx)
1215 assert req.method == "POST"
1217 t = get_arg(req, "t", "").strip()
1219 if t in ("", "upload"):
1220 # "POST /uri", to create an unlinked file.
1221 fileobj = req.fields["file"].file
1222 uploadable = FileHandle(fileobj)
1223 d = IClient(ctx).upload(uploadable)
1224 # that fires with the URI of the new file
1228 # "POST /uri?t=mkdir", to create an unlinked directory.
1229 d = IClient(ctx).create_empty_dirnode()
1230 redirect = get_arg(req, "redirect_to_result", "false")
1231 if boolean_of_arg(redirect):
1232 def _then_redir(res):
1233 new_url = "uri/" + urllib.quote(res.get_uri())
1234 req.setResponseCode(http.SEE_OTHER) # 303
1235 req.setHeader('location', new_url)
1238 d.addCallback(_then_redir)
1240 d.addCallback(lambda dirnode: dirnode.get_uri())
1243 req.setResponseCode(http.BAD_REQUEST)
1244 req.setHeader("content-type", "text/plain")
1245 err = "/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, and POST?t=mkdir"
1249 class Root(rend.Page):
1252 docFactory = getxmlfile("welcome.xhtml")
1254 def locateChild(self, ctx, segments):
1255 client = IClient(ctx)
1256 req = inevow.IRequest(ctx)
1258 segments = list(segments) # XXX HELP I AM YUCKY!
1259 while segments and not segments[-1]:
1263 segments = tuple(segments)
1265 if segments[0] == "uri":
1266 if len(segments) == 1 or segments[1] == '':
1267 uri = get_arg(req, "uri", None)
1269 there = url.URL.fromContext(ctx)
1270 there = there.clear("uri")
1271 there = there.child("uri").child(uri)
1273 if len(segments) == 1:
1275 if req.method == "PUT":
1276 # either "PUT /uri" to create an unlinked file, or
1277 # "PUT /uri?t=mkdir" to create an unlinked directory
1278 return URIPUTHandler(), ()
1279 elif req.method == "POST":
1280 # "POST /uri?t=upload&file=newfile" to upload an unlinked
1281 # file or "POST /uri?t=mkdir" to create a new directory
1282 return URIPOSTHandler(), ()
1283 if len(segments) < 2:
1284 return rend.NotFound
1286 d = defer.maybeDeferred(client.create_node_from_uri, uri)
1287 d.addCallback(lambda node: VDrive(node, "from-uri"))
1288 d.addCallback(lambda vd: vd.locateChild(ctx, segments[2:]))
1289 def _trap_KeyError(f):
1291 return rend.FourOhFour(), ()
1292 d.addErrback(_trap_KeyError)
1294 elif segments[0] == "xmlrpc":
1295 raise NotImplementedError()
1296 return rend.Page.locateChild(self, ctx, segments)
1298 child_webform_css = webform.defaultCSS
1299 child_tahoe_css = nevow_File(util.sibpath(__file__, "web/tahoe.css"))
1301 child_provisioning = provisioning.ProvisioningTool()
1303 def data_version(self, ctx, data):
1304 return get_package_versions_string()
1306 def data_my_nodeid(self, ctx, data):
1307 return b32encode(IClient(ctx).nodeid).lower()
1308 def data_introducer_furl(self, ctx, data):
1309 return IClient(ctx).introducer_furl
1310 def data_connected_to_introducer(self, ctx, data):
1311 if IClient(ctx).connected_to_introducer():
1314 def data_num_peers(self, ctx, data):
1315 #client = inevow.ISite(ctx)._client
1316 client = IClient(ctx)
1317 return len(list(client.get_all_peerids()))
1319 def data_peers(self, ctx, data):
1321 client = IClient(ctx)
1322 for nodeid in sorted(client.get_all_peerids()):
1323 row = (b32encode(nodeid).lower(),)
1327 def render_row(self, ctx, data):
1329 ctx.fillSlots("peerid", nodeid_a)
1332 def render_private_vdrive(self, ctx, data):
1333 basedir = IClient(ctx).basedir
1334 start_html = os.path.abspath(os.path.join(basedir, "private", "start.html"))
1335 basedir = IClient(ctx).basedir
1336 if os.path.exists(start_html) and os.path.exists(os.path.join(basedir, "private", "my_private_dir.cap")):
1337 return T.p["To view your personal private non-shared filestore, ",
1338 "use this browser to open the following file from ",
1339 "your local filesystem:",
1342 return T.p["personal vdrive not available."]
1344 # this is a form where users can download files by URI
1345 def render_download_form(self, ctx, data):
1346 form = T.form(action="uri", method="get",
1347 enctype="multipart/form-data")[
1349 T.legend(class_="freeform-form-label")["download a file"],
1350 "URI of file to download: ",
1351 T.input(type="text", name="uri"), " ",
1352 "Filename to download as: ",
1353 T.input(type="text", name="filename"), " ",
1354 T.input(type="submit", value="download"),
1358 # this is a form where users can create new directories
1359 def render_mkdir_form(self, ctx, data):
1360 form = T.form(action="uri", method="post",
1361 enctype="multipart/form-data")[
1363 T.legend(class_="freeform-form-label")["create a directory"],
1364 T.input(type="hidden", name="t", value="mkdir"),
1365 T.input(type="hidden", name="redirect_to_result", value="true"),
1366 T.input(type="submit", value="create"),
1372 implements(ILocalAccess)
1374 self.local_access = False
1375 def local_access_is_allowed(self):
1376 return self.local_access
1378 class WebishServer(service.MultiService):
1381 def __init__(self, webport):
1382 service.MultiService.__init__(self)
1383 self.webport = webport
1385 self.site = site = appserver.NevowSite(self.root)
1386 self.site.requestFactory = MyRequest
1387 self.allow_local = LocalAccess()
1388 self.site.remember(self.allow_local, ILocalAccess)
1389 s = strports.service(webport, site)
1390 s.setServiceParent(self)
1391 self.listener = s # stash it so the tests can query for the portnum
1392 self._started = defer.Deferred()
1394 def allow_local_access(self, enable=True):
1395 self.allow_local.local_access = enable
1397 def startService(self):
1398 service.MultiService.startService(self)
1399 # to make various services available to render_* methods, we stash a
1400 # reference to the client on the NevowSite. This will be available by
1401 # adapting the 'context' argument to a special marker interface named
1403 self.site.remember(self.parent, IClient)
1404 # I thought you could do the same with an existing interface, but
1405 # apparently 'ISite' does not exist
1406 #self.site._client = self.parent
1407 self._started.callback(None)
1409 def create_start_html(self, private_uri, startfile, nodeurl_file):
1411 Returns a deferred that eventually fires once the start.html page has
1414 self._started.addCallback(self._create_start_html, private_uri, startfile, nodeurl_file)
1415 return self._started
1417 def _create_start_html(self, dummy, private_uri, startfile, nodeurl_file):
1418 f = open(startfile, "w")
1419 template = open(util.sibpath(__file__, "web/start.html"), "r").read()
1420 # what is our webport?
1422 if isinstance(s, internet.TCPServer):
1423 base_url = "http://localhost:%d" % s._port.getHost().port
1424 elif isinstance(s, internet.SSLServer):
1425 base_url = "https://localhost:%d" % s._port.getHost().port
1427 base_url = "UNKNOWN" # this will break the href
1428 # TODO: emit a start.html that explains that we don't know
1429 # how to create a suitable URL
1431 link_to_private_uri = "View <a href=\"%s/uri/%s\">your personal private non-shared filestore</a>." % (base_url, private_uri)
1432 fields = {"link_to_private_uri": link_to_private_uri,
1433 "base_url": base_url,
1436 fields = {"link_to_private_uri": "",
1437 "base_url": base_url,
1439 f.write(template % fields)
1442 f = open(nodeurl_file, "w")
1443 # this file is world-readable
1444 f.write(base_url + "\n")