3 from twisted.application import service, strports, internet
4 from twisted.web import static, resource, server, html, http
5 from twisted.internet import defer, address
6 from twisted.internet.interfaces import IConsumer
7 from nevow import inevow, rend, appserver, url, tags as T
8 from nevow.static import File as nevow_File # TODO: merge with static.File?
9 from allmydata.util import fileutil, idlib, log
11 from allmydata.interfaces import IDownloadTarget, IDirectoryNode, IFileNode, \
13 import allmydata # to display import path
14 from allmydata import download
15 from allmydata.uri import from_string_verifier, CHKFileVerifierURI
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
22 from foolscap.eventual import fireEventually
24 from nevow.util import resource_filename
26 from allmydata.web import status, unlinked, introweb
27 from allmydata.web.common import IClient, getxmlfile, get_arg, \
28 boolean_of_arg, abbreviate_size
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 # we must override twisted.web.http.Request.requestReceived with a version
36 # that doesn't use cgi.parse_multipart() . Since we actually use Nevow, we
37 # override the nevow-specific subclass, nevow.appserver.NevowRequest . This
38 # is an exact copy of twisted.web.http.Request (from SVN HEAD on 10-Aug-2007)
39 # that modifies the way form arguments are parsed. Note that this sort of
40 # surgery may induce a dependency upon a particular version of twisted.web
42 parse_qs = http.parse_qs
43 class MyRequest(appserver.NevowRequest):
45 def requestReceived(self, command, path, version):
46 """Called by channel when all data has been received.
48 This method is not intended for users.
50 self.content.seek(0,0)
54 self.method, self.uri = command, path
55 self.clientproto = version
56 x = self.uri.split('?', 1)
61 self.path, argstring = x
62 self.args = parse_qs(argstring, 1)
64 # cache the client and server information, we'll need this later to be
65 # serialized and sent with the request so CGIs will work remotely
66 self.client = self.channel.transport.getPeer()
67 self.host = self.channel.transport.getHost()
69 # Argument processing.
71 ## The original twisted.web.http.Request.requestReceived code parsed the
72 ## content and added the form fields it found there to self.args . It
73 ## did this with cgi.parse_multipart, which holds the arguments in RAM
74 ## and is thus unsuitable for large file uploads. The Nevow subclass
75 ## (nevow.appserver.NevowRequest) uses cgi.FieldStorage instead (putting
76 ## the results in self.fields), which is much more memory-efficient.
77 ## Since we know we're using Nevow, we can anticipate these arguments
78 ## appearing in self.fields instead of self.args, and thus skip the
79 ## parse-content-into-self.args step.
82 ## ctype = self.getHeader('content-type')
83 ## if self.method == "POST" and ctype:
84 ## mfd = 'multipart/form-data'
85 ## key, pdict = cgi.parse_header(ctype)
86 ## if key == 'application/x-www-form-urlencoded':
87 ## args.update(parse_qs(self.content.read(), 1))
90 ## args.update(cgi.parse_multipart(self.content, pdict))
91 ## except KeyError, e:
92 ## if e.args[0] == 'content-disposition':
93 ## # Parse_multipart can't cope with missing
94 ## # content-dispostion headers in multipart/form-data
95 ## # parts, so we catch the exception and tell the client
96 ## # it was a bad request.
97 ## self.channel.transport.write(
98 ## "HTTP/1.1 400 Bad Request\r\n\r\n")
99 ## self.channel.transport.loseConnection()
106 # we build up a log string that hides most of the cap, to preserve
107 # user privacy. We retain the query args so we can identify things
108 # like t=json. Then we send it to the flog. We make no attempt to
109 # match apache formatting. TODO: when we move to DSA dirnodes and
110 # shorter caps, consider exposing a few characters of the cap, or
111 # maybe a few characters of its hash.
112 x = self.uri.split("?", 1)
119 # there is a form handler which redirects POST /uri?uri=FOO into
120 # GET /uri/FOO so folks can paste in non-HTTP-prefixed uris. Make
121 # sure we censor these too.
122 if queryargs.startswith("uri="):
123 queryargs = "[uri=CENSORED]"
124 queryargs = "?" + queryargs
125 if path.startswith("/uri"):
126 path = "/uri/[CENSORED].."
127 uri = path + queryargs
129 log.msg(format="web: %(clientip)s %(method)s %(uri)s %(code)s %(length)s",
130 clientip=self.getClientIP(),
134 length=(self.sentLength or "-"),
135 facility="tahoe.webish",
136 level=log.OPERATIONAL,
139 class Directory(rend.Page):
141 docFactory = getxmlfile("directory.xhtml")
143 def __init__(self, rootname, dirnode, dirpath):
144 self._rootname = rootname
145 self._dirnode = dirnode
146 self._dirpath = dirpath
148 def dirpath_as_string(self):
149 return "/" + "/".join(self._dirpath)
151 def render_title(self, ctx, data):
152 return ctx.tag["Directory '%s':" % self.dirpath_as_string()]
154 def render_header(self, ctx, data):
155 parent_directories = ("<%s>" % self._rootname,) + self._dirpath
156 num_dirs = len(parent_directories)
158 header = ["Directory '"]
159 for i,d in enumerate(parent_directories):
160 upness = num_dirs - i - 1
162 link = "/".join( ("..",) * upness )
165 header.append(T.a(href=link)[d])
170 if self._dirnode.is_readonly():
171 header.append(" (readonly)")
173 return ctx.tag[header]
175 def render_welcome(self, ctx, data):
176 depth = len(self._dirpath) + 2
177 link = "/".join([".."] * depth)
178 return T.div[T.a(href=link)["Return to Welcome page"]]
180 def data_children(self, ctx, data):
181 d = self._dirnode.list()
182 d.addCallback(lambda dict: sorted(dict.items()))
183 def _stall_some(items):
184 # Deferreds don't optimize out tail recursion, and the way
185 # Nevow's flattener handles Deferreds doesn't take this into
186 # account. As a result, large lists of Deferreds that fire in the
187 # same turn (i.e. the output of defer.succeed) will cause a stack
188 # overflow. To work around this, we insert a turn break after
189 # every 100 items, using foolscap's fireEventually(). This gives
190 # the stack a chance to be popped. It would also work to put
191 # every item in its own turn, but that'd be a lot more
192 # inefficient. This addresses ticket #237, for which I was never
193 # able to create a failing unit test.
195 for i,item in enumerate(items):
197 output.append(fireEventually(item))
201 d.addCallback(_stall_some)
204 def render_row(self, ctx, data):
205 name, (target, metadata) = data
206 name = name.encode("utf-8")
207 assert not isinstance(name, unicode)
209 if self._dirnode.is_readonly():
213 # this creates a button which will cause our child__delete method
214 # to be invoked, which deletes the file and then redirects the
215 # browser back to this directory
216 delete = T.form(action=url.here, method="post")[
217 T.input(type='hidden', name='t', value='delete'),
218 T.input(type='hidden', name='name', value=name),
219 T.input(type='hidden', name='when_done', value=url.here),
220 T.input(type='submit', value='del', name="del"),
223 rename = T.form(action=url.here, method="get")[
224 T.input(type='hidden', name='t', value='rename-form'),
225 T.input(type='hidden', name='name', value=name),
226 T.input(type='hidden', name='when_done', value=url.here),
227 T.input(type='submit', value='rename', name="rename"),
230 ctx.fillSlots("delete", delete)
231 ctx.fillSlots("rename", rename)
232 check = T.form(action=url.here, method="post")[
233 T.input(type='hidden', name='t', value='check'),
234 T.input(type='hidden', name='name', value=name),
235 T.input(type='hidden', name='when_done', value=url.here),
236 T.input(type='submit', value='check', name="check"),
238 ctx.fillSlots("overwrite", self.build_overwrite(ctx, (name, target)))
239 ctx.fillSlots("check", check)
242 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
243 if "ctime" in metadata:
244 ctime = time.strftime(TIME_FORMAT,
245 time.localtime(metadata["ctime"]))
246 times.append("c: " + ctime)
247 if "mtime" in metadata:
248 mtime = time.strftime(TIME_FORMAT,
249 time.localtime(metadata["mtime"]))
252 times.append("m: " + mtime)
253 ctx.fillSlots("times", times)
256 # build the base of the uri_link link url
257 uri_link = "/uri/" + urllib.quote(target.get_uri())
259 assert (IFileNode.providedBy(target)
260 or IDirectoryNode.providedBy(target)
261 or IMutableFileNode.providedBy(target)), target
263 if IMutableFileNode.providedBy(target):
266 # add the filename to the uri_link url
267 uri_link += '?%s' % (urllib.urlencode({'filename': name}),)
269 # to prevent javascript in displayed .html files from stealing a
270 # secret directory URI from the URL, send the browser to a URI-based
271 # page that doesn't know about the directory at all
272 #dlurl = urllib.quote(name)
275 ctx.fillSlots("filename",
276 T.a(href=dlurl)[html.escape(name)])
277 ctx.fillSlots("type", "SSK")
279 ctx.fillSlots("size", "?")
281 text_plain_link = uri_link + "?filename=foo.txt"
282 text_plain_tag = T.a(href=text_plain_link)["text/plain"]
284 elif IFileNode.providedBy(target):
287 # add the filename to the uri_link url
288 uri_link += '?%s' % (urllib.urlencode({'filename': name}),)
290 # to prevent javascript in displayed .html files from stealing a
291 # secret directory URI from the URL, send the browser to a URI-based
292 # page that doesn't know about the directory at all
293 #dlurl = urllib.quote(name)
296 ctx.fillSlots("filename",
297 T.a(href=dlurl)[html.escape(name)])
298 ctx.fillSlots("type", "FILE")
300 ctx.fillSlots("size", target.get_size())
302 text_plain_link = uri_link + "?filename=foo.txt"
303 text_plain_tag = T.a(href=text_plain_link)["text/plain"]
305 elif IDirectoryNode.providedBy(target):
307 ctx.fillSlots("filename",
308 T.a(href=uri_link)[html.escape(name)])
309 if target.is_readonly():
313 ctx.fillSlots("type", dirtype)
314 ctx.fillSlots("size", "-")
315 text_plain_tag = None
317 childdata = [T.a(href="%s?t=json" % name)["JSON"], ", ",
318 T.a(href="%s?t=uri" % name)["URI"], ", ",
319 T.a(href="%s?t=readonly-uri" % name)["readonly-URI"],
322 childdata.extend([", ", text_plain_tag])
324 ctx.fillSlots("data", childdata)
327 checker = IClient(ctx).getServiceNamed("checker")
331 d = defer.maybeDeferred(checker.checker_results_for,
332 target.get_verifier())
333 def _got(checker_results):
334 recent_results = reversed(checker_results[-5:])
335 if IFileNode.providedBy(target):
337 ", ".join(["%d/%d" % (found, needed)
339 (needed, total, found, sharemap))
340 in recent_results]) +
342 elif IDirectoryNode.providedBy(target):
344 "".join([{True:"+",False:"-"}[res]
345 for (when, res) in recent_results]) +
348 results = "%d results" % len(checker_results)
354 # TODO: include a link to see more results, including timestamps
355 # TODO: use a sparkline
356 ctx.fillSlots("checker_results", results)
360 def render_forms(self, ctx, data):
361 if self._dirnode.is_readonly():
362 return T.div["No upload forms: directory is read-only"]
363 mkdir = T.form(action=".", method="post",
364 enctype="multipart/form-data")[
366 T.input(type="hidden", name="t", value="mkdir"),
367 T.input(type="hidden", name="when_done", value=url.here),
368 T.legend(class_="freeform-form-label")["Create a new directory"],
369 "New directory name: ",
370 T.input(type="text", name="name"), " ",
371 T.input(type="submit", value="Create"),
374 upload = T.form(action=".", method="post",
375 enctype="multipart/form-data")[
377 T.input(type="hidden", name="t", value="upload"),
378 T.input(type="hidden", name="when_done", value=url.here),
379 T.legend(class_="freeform-form-label")["Upload a file to this directory"],
380 "Choose a file to upload: ",
381 T.input(type="file", name="file", class_="freeform-input-file"),
383 T.input(type="submit", value="Upload"),
385 T.input(type="checkbox", name="mutable"),
388 mount = T.form(action=".", method="post",
389 enctype="multipart/form-data")[
391 T.input(type="hidden", name="t", value="uri"),
392 T.input(type="hidden", name="when_done", value=url.here),
393 T.legend(class_="freeform-form-label")["Attach a file or directory"
397 T.input(type="text", name="name"), " ",
398 "URI of new child: ",
399 T.input(type="text", name="uri"), " ",
400 T.input(type="submit", value="Attach"),
402 return [T.div(class_="freeform-form")[mkdir],
403 T.div(class_="freeform-form")[upload],
404 T.div(class_="freeform-form")[mount],
407 def build_overwrite(self, ctx, data):
409 if IMutableFileNode.providedBy(target) and not target.is_readonly():
410 action="/uri/" + urllib.quote(target.get_uri())
411 overwrite = T.form(action=action, method="post",
412 enctype="multipart/form-data")[
414 T.input(type="hidden", name="t", value="overwrite"),
415 T.input(type='hidden', name='name', value=name),
416 T.input(type='hidden', name='when_done', value=url.here),
417 T.legend(class_="freeform-form-label")["Overwrite"],
419 T.input(type="file", name="file", class_="freeform-input-file"),
421 T.input(type="submit", value="Overwrite")
423 return [T.div(class_="freeform-form")[overwrite],]
427 def render_results(self, ctx, data):
428 req = inevow.IRequest(ctx)
429 return get_arg(req, "results", "")
431 class WebDownloadTarget:
432 implements(IDownloadTarget, IConsumer)
433 def __init__(self, req, content_type, content_encoding, save_to_file):
435 self._content_type = content_type
436 self._content_encoding = content_encoding
438 self._producer = None
439 self._save_to_file = save_to_file
441 def registerProducer(self, producer, streaming):
442 self._req.registerProducer(producer, streaming)
443 def unregisterProducer(self):
444 self._req.unregisterProducer()
446 def open(self, size):
448 self._req.setHeader("content-type", self._content_type)
449 if self._content_encoding:
450 self._req.setHeader("content-encoding", self._content_encoding)
451 self._req.setHeader("content-length", str(size))
452 if self._save_to_file is not None:
453 # tell the browser to save the file rather display it
454 # TODO: quote save_to_file properly
455 filename = self._save_to_file.encode("utf-8")
456 self._req.setHeader("content-disposition",
457 'attachment; filename="%s"'
460 def write(self, data):
461 self._req.write(data)
467 # The content-type is already set, and the response code
468 # has already been sent, so we can't provide a clean error
469 # indication. We can emit text (which a browser might interpret
470 # as something else), and if we sent a Size header, they might
471 # notice that we've truncated the data. Keep the error message
472 # small to improve the chances of having our error response be
473 # shorter than the intended results.
475 # We don't have a lot of options, unfortunately.
476 self._req.write("problem during download\n")
478 # We haven't written anything yet, so we can provide a sensible
481 msg.replace("\n", "|")
482 self._req.setResponseCode(http.GONE, msg)
483 self._req.setHeader("content-type", "text/plain")
484 # TODO: HTML-formatted exception?
485 self._req.write(str(why))
488 def register_canceller(self, cb):
493 class FileDownloader(resource.Resource):
494 def __init__(self, filenode, name):
495 assert (IFileNode.providedBy(filenode)
496 or IMutableFileNode.providedBy(filenode))
497 self._filenode = filenode
500 def render(self, req):
501 gte = static.getTypeAndEncoding
502 ctype, encoding = gte(self._name,
503 static.File.contentTypes,
504 static.File.contentEncodings,
505 defaultType="text/plain")
507 if get_arg(req, "save", False):
508 # TODO: make the API specification clear: should "save=" or
509 # "save=false" count?
510 save_to_file = self._name
511 wdt = WebDownloadTarget(req, ctype, encoding, save_to_file)
512 d = self._filenode.download(wdt)
513 # exceptions during download are handled by the WebDownloadTarget
514 d.addErrback(lambda why: None)
515 return server.NOT_DONE_YET
517 class BlockingFileError(Exception):
518 """We cannot auto-create a parent directory, because there is a file in
520 class NoReplacementError(Exception):
521 """There was already a child by that name, and you asked me to not replace it"""
522 class NoLocalDirectoryError(Exception):
523 """The localdir= directory didn't exist"""
525 LOCALHOST = "127.0.0.1"
527 class NeedLocalhostError:
528 implements(inevow.IResource)
530 def renderHTTP(self, ctx):
531 req = inevow.IRequest(ctx)
532 req.setResponseCode(http.FORBIDDEN)
533 req.setHeader("content-type", "text/plain")
534 return "localfile= or localdir= requires a local connection"
536 class NeedAbsolutePathError:
537 implements(inevow.IResource)
539 def renderHTTP(self, ctx):
540 req = inevow.IRequest(ctx)
541 req.setResponseCode(http.FORBIDDEN)
542 req.setHeader("content-type", "text/plain")
543 return "localfile= or localdir= requires an absolute path"
545 class LocalAccessDisabledError:
546 implements(inevow.IResource)
548 def renderHTTP(self, ctx):
549 req = inevow.IRequest(ctx)
550 req.setResponseCode(http.FORBIDDEN)
551 req.setHeader("content-type", "text/plain")
552 return "local file access is disabled"
555 implements(inevow.IResource)
556 def __init__(self, response_code, errmsg):
557 self._response_code = response_code
558 self._errmsg = errmsg
560 def renderHTTP(self, ctx):
561 req = inevow.IRequest(ctx)
562 req.setResponseCode(self._response_code)
563 req.setHeader("content-type", "text/plain")
567 class LocalFileDownloader(resource.Resource):
568 def __init__(self, filenode, local_filename):
569 self._local_filename = local_filename
571 self._filenode = filenode
573 def render(self, req):
574 target = download.FileName(self._local_filename)
575 d = self._filenode.download(target)
577 req.write(self._filenode.get_uri())
580 return server.NOT_DONE_YET
583 class FileJSONMetadata(rend.Page):
584 def __init__(self, filenode):
585 self._filenode = filenode
587 def renderHTTP(self, ctx):
588 req = inevow.IRequest(ctx)
589 req.setHeader("content-type", "text/plain")
590 return self.renderNode(self._filenode)
592 def renderNode(self, filenode):
593 file_uri = filenode.get_uri()
596 'size': filenode.get_size(),
598 return simplejson.dumps(data, indent=1)
600 class FileURI(FileJSONMetadata):
601 def renderNode(self, filenode):
602 file_uri = filenode.get_uri()
605 class FileReadOnlyURI(FileJSONMetadata):
606 def renderNode(self, filenode):
607 if filenode.is_readonly():
608 return filenode.get_uri()
610 return filenode.get_readonly().get_uri()
612 class DirnodeWalkerMixin:
613 """Visit all nodes underneath (and including) the rootnode, one at a
614 time. For each one, call the visitor. The visitor will see the
615 IDirectoryNode before it sees any of the IFileNodes inside. If the
616 visitor returns a Deferred, I do not call the visitor again until it has
620 ## def _walk_if_we_could_use_generators(self, rootnode, rootpath=()):
621 ## # this is what we'd be doing if we didn't have the Deferreds and
622 ## # thus could use generators
623 ## yield rootpath, rootnode
624 ## for childname, childnode in rootnode.list().items():
625 ## childpath = rootpath + (childname,)
626 ## if IFileNode.providedBy(childnode):
627 ## yield childpath, childnode
628 ## elif IDirectoryNode.providedBy(childnode):
629 ## for res in self._walk_if_we_could_use_generators(childnode,
633 def walk(self, rootnode, visitor, rootpath=()):
635 def _listed(listing):
636 return listing.items()
637 d.addCallback(_listed)
638 d.addCallback(self._handle_items, visitor, rootpath)
641 def _handle_items(self, items, visitor, rootpath):
644 childname, (childnode, metadata) = items[0]
645 childpath = rootpath + (childname,)
646 d = defer.maybeDeferred(visitor, childpath, childnode, metadata)
647 if IDirectoryNode.providedBy(childnode):
648 d.addCallback(lambda res: self.walk(childnode, visitor, childpath))
649 d.addCallback(lambda res:
650 self._handle_items(items[1:], visitor, rootpath))
653 class LocalDirectoryDownloader(resource.Resource, DirnodeWalkerMixin):
654 def __init__(self, dirnode, localdir):
655 self._dirnode = dirnode
656 self._localdir = localdir
658 def _handle(self, path, node, metadata):
659 path = tuple([p.encode("utf-8") for p in path])
660 localfile = os.path.join(self._localdir, os.sep.join(path))
661 if IDirectoryNode.providedBy(node):
662 fileutil.make_dirs(localfile)
663 elif IFileNode.providedBy(node):
664 target = download.FileName(localfile)
665 return node.download(target)
667 def render(self, req):
668 d = self.walk(self._dirnode, self._handle)
670 req.setHeader("content-type", "text/plain")
671 return "operation complete"
675 class DirectoryJSONMetadata(rend.Page):
676 def __init__(self, dirnode):
677 self._dirnode = dirnode
679 def renderHTTP(self, ctx):
680 req = inevow.IRequest(ctx)
681 req.setHeader("content-type", "text/plain")
682 return self.renderNode(self._dirnode)
684 def renderNode(self, node):
688 for name, (childnode, metadata) in children.iteritems():
689 if IFileNode.providedBy(childnode):
690 kiduri = childnode.get_uri()
691 kiddata = ("filenode",
693 'size': childnode.get_size(),
694 'metadata': metadata,
697 assert IDirectoryNode.providedBy(childnode), (childnode, children,)
698 kiddata = ("dirnode",
699 {'ro_uri': childnode.get_readonly_uri(),
700 'metadata': metadata,
702 if not childnode.is_readonly():
703 kiddata[1]['rw_uri'] = childnode.get_uri()
705 contents = { 'children': kids,
706 'ro_uri': node.get_readonly_uri(),
708 if not node.is_readonly():
709 contents['rw_uri'] = node.get_uri()
710 data = ("dirnode", contents)
711 return simplejson.dumps(data, indent=1)
715 class DirectoryURI(DirectoryJSONMetadata):
716 def renderNode(self, node):
717 return node.get_uri()
719 class DirectoryReadonlyURI(DirectoryJSONMetadata):
720 def renderNode(self, node):
721 return node.get_readonly_uri()
723 class RenameForm(rend.Page):
725 docFactory = getxmlfile("rename-form.xhtml")
727 def __init__(self, rootname, dirnode, dirpath):
728 self._rootname = rootname
729 self._dirnode = dirnode
730 self._dirpath = dirpath
732 def dirpath_as_string(self):
733 return "/" + "/".join(self._dirpath)
735 def render_title(self, ctx, data):
736 return ctx.tag["Directory '%s':" % self.dirpath_as_string()]
738 def render_header(self, ctx, data):
739 parent_directories = ("<%s>" % self._rootname,) + self._dirpath
740 num_dirs = len(parent_directories)
742 header = [ "Rename in directory '",
743 "<%s>/" % self._rootname,
744 "/".join(self._dirpath),
747 if self._dirnode.is_readonly():
748 header.append(" (readonly)")
749 return ctx.tag[header]
751 def render_when_done(self, ctx, data):
752 return T.input(type="hidden", name="when_done", value=url.here)
754 def render_get_name(self, ctx, data):
755 req = inevow.IRequest(ctx)
756 name = get_arg(req, "name", "")
757 ctx.tag.attributes['value'] = name
760 class POSTHandler(rend.Page):
761 def __init__(self, node, replace):
763 self._replace = replace
765 def _check_replacement(self, name):
767 return defer.succeed(None)
768 d = self._node.has_child(name)
771 raise NoReplacementError("There was already a child by that "
772 "name, and you asked me to not "
778 def _POST_mkdir(self, name):
779 d = self._check_replacement(name)
780 d.addCallback(lambda res: self._node.create_empty_directory(name))
781 d.addCallback(lambda res: "directory created")
784 def _POST_mkdir_p(self, path):
785 path_ = tuple([seg.decode("utf-8") for seg in path.split('/') if seg ])
786 d = self._get_or_create_directories(self._node, path_)
787 d.addCallback(lambda node: node.get_uri())
790 # this code stolen from PUTHandler: should be refactored to a more
791 # generally accesible place, perhaps...
792 def _get_or_create_directories(self, node, path):
793 if not IDirectoryNode.providedBy(node):
794 # unfortunately it is too late to provide the name of the
795 # blocking directory in the error message.
796 raise BlockingFileError("cannot create directory because there "
797 "is a file in the way")
799 return defer.succeed(node)
800 d = node.get(path[0])
801 def _maybe_create(f):
803 return node.create_empty_directory(path[0])
804 d.addErrback(_maybe_create)
805 d.addCallback(self._get_or_create_directories, path[1:])
808 def _POST_uri(self, name, newuri):
809 d = self._check_replacement(name)
810 d.addCallback(lambda res: self._node.set_uri(name, newuri))
811 d.addCallback(lambda res: newuri)
814 def _POST_delete(self, name):
816 # apparently an <input type="hidden" name="name" value="">
817 # won't show up in the resulting encoded form.. the 'name'
818 # field is completely missing. So to allow deletion of an
819 # empty file, we have to pretend that None means ''. The only
820 # downide of this is a slightly confusing error message if
821 # someone does a POST without a name= field. For our own HTML
822 # thisn't a big deal, because we create the 'delete' POST
825 d = self._node.delete(name)
826 d.addCallback(lambda res: "thing deleted")
829 def _POST_rename(self, name, from_name, to_name):
830 d = self._check_replacement(to_name)
831 d.addCallback(lambda res: self._node.get(from_name))
833 uri = child.get_uri()
834 # now actually do the rename
835 return self._node.set_uri(to_name, uri)
836 d.addCallback(add_dest)
838 return self._node.delete(from_name)
839 d.addCallback(rm_src)
840 d.addCallback(lambda res: "thing renamed")
843 def _POST_upload(self, contents, name, mutable, client):
845 # SDMF: files are small, and we can only upload data.
846 contents.file.seek(0)
847 data = contents.file.read()
848 #uploadable = FileHandle(contents.file)
849 d = self._check_replacement(name)
850 d.addCallback(lambda res: self._node.has_child(name))
851 def _checked(present):
853 # modify the existing one instead of creating a new
855 d2 = self._node.get(name)
856 def _got_newnode(newnode):
857 d3 = newnode.overwrite(data)
858 d3.addCallback(lambda res: newnode.get_uri())
860 d2.addCallback(_got_newnode)
862 d2 = client.create_mutable_file(data)
863 def _uploaded(newnode):
864 d1 = self._node.set_node(name, newnode)
865 d1.addCallback(lambda res: newnode.get_uri())
867 d2.addCallback(_uploaded)
869 d.addCallback(_checked)
871 uploadable = FileHandle(contents.file, convergence=client.convergence)
872 d = self._check_replacement(name)
873 d.addCallback(lambda res: self._node.add_file(name, uploadable))
875 return newnode.get_uri()
879 def _POST_overwrite(self, contents):
880 # SDMF: files are small, and we can only upload data.
881 contents.file.seek(0)
882 data = contents.file.read()
883 # TODO: 'name' handling needs review
884 d = defer.succeed(self._node)
885 def _got_child_overwrite(child_node):
886 child_node.overwrite(data)
887 return child_node.get_uri()
888 d.addCallback(_got_child_overwrite)
891 def _POST_check(self, name):
892 d = self._node.get(name)
893 def _got_child_check(child_node):
894 d2 = child_node.check()
896 log.msg("checked %s, results %s" % (child_node, res),
897 facility="tahoe.webish", level=log.NOISY)
899 d2.addCallback(_done)
901 d.addCallback(_got_child_check)
904 def _POST_set_children(self, children):
906 for name, (file_or_dir, mddict) in children.iteritems():
907 cap = str(mddict.get('rw_uri') or mddict.get('ro_uri'))
908 cs.append((name, cap, mddict.get('metadata')))
910 d = self._node.set_children(cs)
911 d.addCallback(lambda res: "Okay so I did it.")
914 def renderHTTP(self, ctx):
915 req = inevow.IRequest(ctx)
917 t = get_arg(req, "t")
920 charset = get_arg(req, "_charset", "utf-8")
922 name = get_arg(req, "name", None)
923 if name and "/" in name:
924 req.setResponseCode(http.BAD_REQUEST)
925 req.setHeader("content-type", "text/plain")
926 return "name= may not contain a slash"
929 name = name.decode(charset)
930 assert isinstance(name, unicode)
931 # we allow the user to delete an empty-named file, but not to create
932 # them, since that's an easy and confusing mistake to make
934 when_done = get_arg(req, "when_done", None)
935 if not boolean_of_arg(get_arg(req, "replace", "true")):
936 self._replace = False
940 raise RuntimeError("mkdir requires a name")
941 d = self._POST_mkdir(name)
943 path = get_arg(req, "path")
945 raise RuntimeError("mkdir-p requires a path")
946 d = self._POST_mkdir_p(path)
949 raise RuntimeError("set-uri requires a name")
950 newuri = get_arg(req, "uri")
951 assert newuri is not None
952 d = self._POST_uri(name, newuri)
954 d = self._POST_delete(name)
956 from_name = get_arg(req, "from_name")
957 if from_name is not None:
958 from_name = from_name.strip()
959 from_name = from_name.decode(charset)
960 assert isinstance(from_name, unicode)
961 to_name = get_arg(req, "to_name")
962 if to_name is not None:
963 to_name = to_name.strip()
964 to_name = to_name.decode(charset)
965 assert isinstance(to_name, unicode)
966 if not from_name or not to_name:
967 raise RuntimeError("rename requires from_name and to_name")
968 if not IDirectoryNode.providedBy(self._node):
969 raise RuntimeError("rename must only be called on directories")
970 for k,v in [ ('from_name', from_name), ('to_name', to_name) ]:
972 req.setResponseCode(http.BAD_REQUEST)
973 req.setHeader("content-type", "text/plain")
974 return "%s= may not contain a slash" % (k,)
975 d = self._POST_rename(name, from_name, to_name)
977 contents = req.fields["file"]
978 name = name or contents.filename
982 # this prohibts empty, missing, and all-whitespace filenames
983 raise RuntimeError("upload requires a name")
984 name = name.decode(charset)
985 assert isinstance(name, unicode)
986 mutable = boolean_of_arg(get_arg(req, "mutable", "false"))
987 d = self._POST_upload(contents, name, mutable, IClient(ctx))
988 elif t == "overwrite":
989 contents = req.fields["file"]
990 d = self._POST_overwrite(contents)
992 d = self._POST_check(name)
993 elif t == "set_children":
995 body = req.content.read()
997 children = simplejson.loads(body)
998 except ValueError, le:
999 le.args = tuple(le.args + (body,))
1000 # TODO test handling of bad JSON
1002 d = self._POST_set_children(children)
1004 req.setResponseCode(http.BAD_REQUEST)
1005 req.setHeader("content-type", "text/plain")
1006 return "BAD t=%s" % t
1008 d.addCallback(lambda res: url.URL.fromString(when_done))
1009 def _check_replacement(f):
1010 # TODO: make this more human-friendly: maybe send them to the
1011 # when_done page but with an extra query-arg that will display
1012 # the error message in a big box at the top of the page. The
1013 # directory page that when_done= usually points to accepts a
1014 # result= argument.. use that.
1015 f.trap(NoReplacementError)
1016 req.setResponseCode(http.CONFLICT)
1017 req.setHeader("content-type", "text/plain")
1019 d.addErrback(_check_replacement)
1022 class DELETEHandler(rend.Page):
1023 def __init__(self, node, name):
1027 def renderHTTP(self, ctx):
1028 req = inevow.IRequest(ctx)
1029 d = self._node.delete(self._name)
1031 # what should this return??
1032 return "%s deleted" % self._name.encode("utf-8")
1033 d.addCallback(_done)
1034 def _trap_missing(f):
1036 req.setResponseCode(http.NOT_FOUND)
1037 req.setHeader("content-type", "text/plain")
1038 return "no such child %s" % self._name.encode("utf-8")
1039 d.addErrback(_trap_missing)
1042 class PUTHandler(rend.Page):
1043 def __init__(self, node, path, t, localfile, localdir, replace):
1047 self._localfile = localfile
1048 self._localdir = localdir
1049 self._replace = replace
1051 def renderHTTP(self, ctx):
1052 client = IClient(ctx)
1053 req = inevow.IRequest(ctx)
1055 localfile = self._localfile
1056 localdir = self._localdir
1058 if t == "upload" and not (localfile or localdir):
1059 req.setResponseCode(http.BAD_REQUEST)
1060 req.setHeader("content-type", "text/plain")
1061 return "t=upload requires localfile= or localdir="
1063 # we must traverse the path, creating new directories as necessary
1064 d = self._get_or_create_directories(self._node, self._path[:-1])
1065 name = self._path[-1]
1066 d.addCallback(self._check_replacement, name, self._replace)
1069 d.addCallback(self._upload_localfile, localfile, name, convergence=client.convergence)
1072 # take the last step
1073 d.addCallback(self._get_or_create_directories, self._path[-1:])
1074 d.addCallback(self._upload_localdir, localdir, convergence=client.convergence)
1076 d.addCallback(self._attach_uri, req.content, name)
1078 d.addCallback(self._mkdir, name)
1080 d.addCallback(self._upload_file, req.content, name, convergence=client.convergence)
1082 def _transform_error(f):
1083 errors = {BlockingFileError: http.BAD_REQUEST,
1084 NoReplacementError: http.CONFLICT,
1085 NoLocalDirectoryError: http.BAD_REQUEST,
1087 for k,v in errors.items():
1089 req.setResponseCode(v)
1090 req.setHeader("content-type", "text/plain")
1093 d.addErrback(_transform_error)
1096 def _get_or_create_directories(self, node, path):
1097 if not IDirectoryNode.providedBy(node):
1098 # unfortunately it is too late to provide the name of the
1099 # blocking directory in the error message.
1100 raise BlockingFileError("cannot create directory because there "
1101 "is a file in the way")
1103 return defer.succeed(node)
1104 d = node.get(path[0])
1105 def _maybe_create(f):
1107 return node.create_empty_directory(path[0])
1108 d.addErrback(_maybe_create)
1109 d.addCallback(self._get_or_create_directories, path[1:])
1112 def _check_replacement(self, node, name, replace):
1115 d = node.has_child(name)
1118 raise NoReplacementError("There was already a child by that "
1119 "name, and you asked me to not "
1125 def _mkdir(self, node, name):
1126 d = node.create_empty_directory(name)
1128 return newnode.get_uri()
1129 d.addCallback(_done)
1132 def _upload_file(self, node, contents, name, convergence):
1133 uploadable = FileHandle(contents, convergence=convergence)
1134 d = node.add_file(name, uploadable)
1135 def _done(filenode):
1136 log.msg("webish upload complete",
1137 facility="tahoe.webish", level=log.NOISY)
1138 return filenode.get_uri()
1139 d.addCallback(_done)
1142 def _upload_localfile(self, node, localfile, name, convergence):
1143 uploadable = FileName(localfile, convergence=convergence)
1144 d = node.add_file(name, uploadable)
1145 d.addCallback(lambda filenode: filenode.get_uri())
1148 def _attach_uri(self, parentnode, contents, name):
1149 newuri = contents.read().strip()
1150 d = parentnode.set_uri(name, newuri)
1153 d.addCallback(_done)
1156 def _upload_localdir(self, node, localdir, convergence):
1157 # build up a list of files to upload. TODO: for now, these files and
1158 # directories must have UTF-8 encoded filenames: anything else will
1159 # cause the upload to break.
1162 msg = "No files to upload! %s is empty" % localdir
1163 if not os.path.exists(localdir):
1164 msg = "%s doesn't exist!" % localdir
1165 raise NoLocalDirectoryError(msg)
1166 for root, dirs, files in os.walk(localdir):
1167 if root == localdir:
1170 relative_root = root[len(localdir)+1:]
1171 path = tuple(relative_root.split(os.sep))
1173 this_dir = path + (d,)
1174 this_dir = tuple([p.decode("utf-8") for p in this_dir])
1175 all_dirs.append(this_dir)
1177 this_file = path + (f,)
1178 this_file = tuple([p.decode("utf-8") for p in this_file])
1179 all_files.append(this_file)
1180 d = defer.succeed(msg)
1181 for dir in all_dirs:
1183 d.addCallback(self._makedir, node, dir)
1185 d.addCallback(self._upload_one_file, node, localdir, f, convergence=convergence)
1188 def _makedir(self, res, node, dir):
1189 d = defer.succeed(None)
1190 # get the parent. As long as os.walk gives us parents before
1191 # children, this ought to work
1192 d.addCallback(lambda res: node.get_child_at_path(dir[:-1]))
1193 # then create the child directory
1194 d.addCallback(lambda parent: parent.create_empty_directory(dir[-1]))
1197 def _upload_one_file(self, res, node, localdir, f, convergence):
1198 # get the parent. We can be sure this exists because we already
1199 # went through and created all the directories we require.
1200 localfile = os.path.join(localdir, *f)
1201 d = node.get_child_at_path(f[:-1])
1202 d.addCallback(self._upload_localfile, localfile, f[-1], convergence=convergence)
1206 class Manifest(rend.Page):
1207 docFactory = getxmlfile("manifest.xhtml")
1208 def __init__(self, dirnode, dirpath):
1209 self._dirnode = dirnode
1210 self._dirpath = dirpath
1212 def dirpath_as_string(self):
1213 return "/" + "/".join(self._dirpath)
1215 def render_title(self, ctx):
1216 return T.title["Manifest of %s" % self.dirpath_as_string()]
1218 def render_header(self, ctx):
1219 return T.p["Manifest of %s" % self.dirpath_as_string()]
1221 def data_items(self, ctx, data):
1222 return self._dirnode.build_manifest()
1224 def render_row(self, ctx, refresh_cap):
1225 ctx.fillSlots("refresh_capability", refresh_cap)
1228 class DeepSize(rend.Page):
1230 def __init__(self, dirnode, dirpath):
1231 self._dirnode = dirnode
1232 self._dirpath = dirpath
1234 def renderHTTP(self, ctx):
1235 inevow.IRequest(ctx).setHeader("content-type", "text/plain")
1236 d = self._dirnode.build_manifest()
1237 def _measure_size(manifest):
1239 for verifiercap in manifest:
1240 u = from_string_verifier(verifiercap)
1241 if isinstance(u, CHKFileVerifierURI):
1244 d.addCallback(_measure_size)
1248 implements(inevow.IResource)
1249 def renderHTTP(self, ctx):
1250 req = inevow.IRequest(ctx)
1251 req.setResponseCode(http.BAD_REQUEST)
1252 req.setHeader("content-type", "text/plain")
1255 def child_error(text):
1260 class VDrive(rend.Page):
1262 def __init__(self, node, name):
1266 def get_child_at_path(self, path):
1268 return self.node.get_child_at_path(path)
1269 return defer.succeed(self.node)
1271 def locateChild(self, ctx, segments):
1272 req = inevow.IRequest(ctx)
1274 path = tuple([seg.decode("utf-8") for seg in segments])
1276 t = get_arg(req, "t", "")
1277 localfile = get_arg(req, "localfile", None)
1278 if localfile is not None:
1279 if localfile != os.path.abspath(localfile):
1280 return NeedAbsolutePathError(), ()
1281 localdir = get_arg(req, "localdir", None)
1282 if localdir is not None:
1283 if localdir != os.path.abspath(localdir):
1284 return NeedAbsolutePathError(), ()
1285 if localfile or localdir:
1286 if not ILocalAccess(ctx).local_access_is_allowed():
1287 return LocalAccessDisabledError(), ()
1288 if req.getHost().host != LOCALHOST:
1289 return NeedLocalhostError(), ()
1290 # TODO: think about clobbering/revealing config files and node secrets
1292 replace = boolean_of_arg(get_arg(req, "replace", "true"))
1295 # the node must exist, and our operation will be performed on the
1297 d = self.get_child_at_path(path)
1298 def file_or_dir(node):
1299 if (IFileNode.providedBy(node)
1300 or IMutableFileNode.providedBy(node)):
1301 filename = "unknown"
1304 filename = get_arg(req, "filename", filename)
1307 # write contents to a local file
1308 return LocalFileDownloader(node, localfile), ()
1309 # send contents as the result
1310 return FileDownloader(node, filename), ()
1312 # send contents as the result
1313 return FileDownloader(node, filename), ()
1315 return FileJSONMetadata(node), ()
1317 return FileURI(node), ()
1318 elif t == "readonly-uri":
1319 return FileReadOnlyURI(node), ()
1321 return child_error("bad t=%s" % t)
1322 elif IDirectoryNode.providedBy(node):
1325 # recursive download to a local directory
1326 return LocalDirectoryDownloader(node, localdir), ()
1327 return child_error("t=download requires localdir=")
1329 # send an HTML representation of the directory
1330 return Directory(self.name, node, path), ()
1332 return DirectoryJSONMetadata(node), ()
1334 return DirectoryURI(node), ()
1335 elif t == "readonly-uri":
1336 return DirectoryReadonlyURI(node), ()
1337 elif t == "manifest":
1338 return Manifest(node, path), ()
1339 elif t == "deep-size":
1340 return DeepSize(node, path), ()
1341 elif t == 'rename-form':
1342 return RenameForm(self.name, node, path), ()
1344 return child_error("bad t=%s" % t)
1346 return child_error("unknown node type")
1347 d.addCallback(file_or_dir)
1348 elif method == "POST":
1349 # the node must exist, and our operation will be performed on the
1351 d = self.get_child_at_path(path)
1352 def _got_POST(node):
1353 return POSTHandler(node, replace), ()
1354 d.addCallback(_got_POST)
1355 elif method == "DELETE":
1356 # the node must exist, and our operation will be performed on its
1358 assert path # you can't delete the root
1359 d = self.get_child_at_path(path[:-1])
1360 def _got_DELETE(node):
1361 return DELETEHandler(node, path[-1]), ()
1362 d.addCallback(_got_DELETE)
1363 elif method in ("PUT",):
1364 # the node may or may not exist, and our operation may involve
1365 # all the ancestors of the node.
1366 return PUTHandler(self.node, path, t, localfile, localdir, replace), ()
1368 return rend.NotFound
1371 class Root(rend.Page):
1374 docFactory = getxmlfile("welcome.xhtml")
1376 def locateChild(self, ctx, segments):
1377 client = IClient(ctx)
1378 req = inevow.IRequest(ctx)
1380 if not segments or segments[0] != "uri":
1381 return rend.Page.locateChild(self, ctx, segments)
1383 segments = list(segments)
1384 while segments and not segments[-1]:
1388 segments = tuple(segments)
1390 if len(segments) == 1 or segments[1] == '':
1391 uri = get_arg(req, "uri", None)
1393 there = url.URL.fromContext(ctx)
1394 there = there.clear("uri")
1395 there = there.child("uri").child(uri)
1398 if len(segments) == 1:
1400 if req.method == "PUT":
1401 # either "PUT /uri" to create an unlinked file, or
1402 # "PUT /uri?t=mkdir" to create an unlinked directory
1403 t = get_arg(req, "t", "").strip()
1405 mutable = bool(get_arg(req, "mutable", "").strip())
1407 return unlinked.UnlinkedPUTSSKUploader(), ()
1409 return unlinked.UnlinkedPUTCHKUploader(), ()
1411 return unlinked.UnlinkedPUTCreateDirectory(), ()
1412 errmsg = "/uri only accepts PUT and PUT?t=mkdir"
1413 return WebError(http.BAD_REQUEST, errmsg), ()
1415 elif req.method == "POST":
1416 # "POST /uri?t=upload&file=newfile" to upload an
1417 # unlinked file or "POST /uri?t=mkdir" to create a
1419 t = get_arg(req, "t", "").strip()
1420 if t in ("", "upload"):
1421 mutable = bool(get_arg(req, "mutable", "").strip())
1423 return unlinked.UnlinkedPOSTSSKUploader(), ()
1425 return unlinked.UnlinkedPOSTCHKUploader(client, req), ()
1427 return unlinked.UnlinkedPOSTCreateDirectory(), ()
1428 errmsg = "/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, and POST?t=mkdir"
1429 return WebError(http.BAD_REQUEST, errmsg), ()
1431 if len(segments) < 2:
1432 return rend.NotFound
1435 d = defer.maybeDeferred(client.create_node_from_uri, uri)
1436 d.addCallback(lambda node: VDrive(node, uri))
1437 d.addCallback(lambda vd: vd.locateChild(ctx, segments[2:]))
1438 def _trap_KeyError(f):
1440 return rend.FourOhFour(), ()
1441 d.addErrback(_trap_KeyError)
1444 child_webform_css = webform.defaultCSS
1445 child_tahoe_css = nevow_File(resource_filename('allmydata.web', 'tahoe.css'))
1447 child_provisioning = provisioning.ProvisioningTool()
1448 child_status = status.Status()
1449 child_helper_status = status.HelperStatus()
1450 child_statistics = status.Statistics()
1452 def data_version(self, ctx, data):
1453 return get_package_versions_string()
1454 def data_import_path(self, ctx, data):
1455 return str(allmydata)
1456 def data_my_nodeid(self, ctx, data):
1457 return idlib.nodeid_b2a(IClient(ctx).nodeid)
1459 def render_services(self, ctx, data):
1461 client = IClient(ctx)
1463 ss = client.getServiceNamed("storage")
1464 allocated_s = abbreviate_size(ss.allocated_size())
1465 allocated = "about %s allocated" % allocated_s
1466 sizelimit = "no size limit"
1467 if ss.sizelimit is not None:
1468 sizelimit = "size limit is %s" % abbreviate_size(ss.sizelimit)
1469 ul[T.li["Storage Server: %s, %s" % (allocated, sizelimit)]]
1471 ul[T.li["Not running storage server"]]
1474 h = client.getServiceNamed("helper")
1475 stats = h.get_stats()
1476 active_uploads = stats["chk_upload_helper.active_uploads"]
1477 ul[T.li["Helper: %d active uploads" % (active_uploads,)]]
1479 ul[T.li["Not running helper"]]
1483 def data_introducer_furl(self, ctx, data):
1484 return IClient(ctx).introducer_furl
1485 def data_connected_to_introducer(self, ctx, data):
1486 if IClient(ctx).connected_to_introducer():
1490 def data_helper_furl(self, ctx, data):
1492 uploader = IClient(ctx).getServiceNamed("uploader")
1495 furl, connected = uploader.get_helper_info()
1497 def data_connected_to_helper(self, ctx, data):
1499 uploader = IClient(ctx).getServiceNamed("uploader")
1501 return "no" # we don't even have an Uploader
1502 furl, connected = uploader.get_helper_info()
1507 def data_known_storage_servers(self, ctx, data):
1508 ic = IClient(ctx).introducer_client
1510 for c in ic.get_all_connectors().values()
1511 if c.service_name == "storage"]
1514 def data_connected_storage_servers(self, ctx, data):
1515 ic = IClient(ctx).introducer_client
1516 return len(ic.get_all_connections_for("storage"))
1518 def data_services(self, ctx, data):
1519 ic = IClient(ctx).introducer_client
1520 c = [ (service_name, nodeid, rsc)
1521 for (nodeid, service_name), rsc
1522 in ic.get_all_connectors().items() ]
1526 def render_service_row(self, ctx, data):
1527 (service_name, nodeid, rsc) = data
1528 ctx.fillSlots("peerid", "%s %s" % (idlib.nodeid_b2a(nodeid),
1531 rhost = rsc.remote_host
1532 if nodeid == IClient(ctx).nodeid:
1533 rhost_s = "(loopback)"
1534 elif isinstance(rhost, address.IPv4Address):
1535 rhost_s = "%s:%d" % (rhost.host, rhost.port)
1537 rhost_s = str(rhost)
1538 connected = "Yes: to " + rhost_s
1539 since = rsc.last_connect_time
1542 since = rsc.last_loss_time
1544 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
1545 ctx.fillSlots("connected", connected)
1546 ctx.fillSlots("since", time.strftime(TIME_FORMAT, time.localtime(since)))
1547 ctx.fillSlots("announced", time.strftime(TIME_FORMAT,
1548 time.localtime(rsc.announcement_time)))
1549 ctx.fillSlots("version", rsc.version)
1550 ctx.fillSlots("service_name", rsc.service_name)
1554 def render_download_form(self, ctx, data):
1555 # this is a form where users can download files by URI
1556 form = T.form(action="uri", method="get",
1557 enctype="multipart/form-data")[
1559 T.legend(class_="freeform-form-label")["Download a file"],
1560 "URI to download: ",
1561 T.input(type="text", name="uri"), " ",
1562 "Filename to download as: ",
1563 T.input(type="text", name="filename"), " ",
1564 T.input(type="submit", value="Download!"),
1568 def render_view_form(self, ctx, data):
1569 # this is a form where users can download files by URI, or jump to a
1571 form = T.form(action="uri", method="get",
1572 enctype="multipart/form-data")[
1574 T.legend(class_="freeform-form-label")["View a file or directory"],
1576 T.input(type="text", name="uri"), " ",
1577 T.input(type="submit", value="View!"),
1581 def render_upload_form(self, ctx, data):
1582 # this is a form where users can upload unlinked files
1583 form = T.form(action="uri", method="post",
1584 enctype="multipart/form-data")[
1586 T.legend(class_="freeform-form-label")["Upload a file"],
1588 T.input(type="file", name="file", class_="freeform-input-file"),
1589 T.input(type="hidden", name="t", value="upload"),
1590 " Mutable?:", T.input(type="checkbox", name="mutable"),
1591 T.input(type="submit", value="Upload!"),
1595 def render_mkdir_form(self, ctx, data):
1596 # this is a form where users can create new directories
1597 form = T.form(action="uri", method="post",
1598 enctype="multipart/form-data")[
1600 T.legend(class_="freeform-form-label")["Create a directory"],
1601 T.input(type="hidden", name="t", value="mkdir"),
1602 T.input(type="hidden", name="redirect_to_result", value="true"),
1603 T.input(type="submit", value="Create Directory!"),
1609 implements(ILocalAccess)
1611 self.local_access = False
1612 def local_access_is_allowed(self):
1613 return self.local_access
1615 class WebishServer(service.MultiService):
1619 def __init__(self, webport, nodeurl_path=None):
1620 service.MultiService.__init__(self)
1621 self.webport = webport
1622 self.root = self.root_class()
1623 self.site = site = appserver.NevowSite(self.root)
1624 self.site.requestFactory = MyRequest
1625 self.allow_local = LocalAccess()
1626 self.site.remember(self.allow_local, ILocalAccess)
1627 s = strports.service(webport, site)
1628 s.setServiceParent(self)
1629 self.listener = s # stash it so the tests can query for the portnum
1630 self._started = defer.Deferred()
1632 self._started.addCallback(self._write_nodeurl_file, nodeurl_path)
1634 def allow_local_access(self, enable=True):
1635 self.allow_local.local_access = enable
1637 def startService(self):
1638 service.MultiService.startService(self)
1639 # to make various services available to render_* methods, we stash a
1640 # reference to the client on the NevowSite. This will be available by
1641 # adapting the 'context' argument to a special marker interface named
1643 self.site.remember(self.parent, IClient)
1644 # I thought you could do the same with an existing interface, but
1645 # apparently 'ISite' does not exist
1646 #self.site._client = self.parent
1647 self._started.callback(None)
1649 def _write_nodeurl_file(self, junk, nodeurl_path):
1650 # what is our webport?
1652 if isinstance(s, internet.TCPServer):
1653 base_url = "http://127.0.0.1:%d/" % s._port.getHost().port
1654 elif isinstance(s, internet.SSLServer):
1655 base_url = "https://127.0.0.1:%d/" % s._port.getHost().port
1659 f = open(nodeurl_path, 'wb')
1660 # this file is world-readable
1661 f.write(base_url + "\n")
1664 class IntroducerWebishServer(WebishServer):
1665 root_class = introweb.IntroducerRoot