5 from zope.interface import implements
6 from twisted.internet import defer
7 from twisted.internet.interfaces import IPushProducer
8 from twisted.python.failure import Failure
9 from twisted.web import http, html
10 from nevow import url, rend, inevow, tags as T
11 from nevow.inevow import IRequest
13 from foolscap.api import fireEventually
15 from allmydata.util import base32, time_format
16 from allmydata.uri import from_string_dirnode
17 from allmydata.interfaces import IDirectoryNode, IFileNode, IFilesystemNode, \
18 IImmutableFileNode, IMutableFileNode, ExistingChildError, \
19 NoSuchChildError, EmptyPathnameComponentError, SDMF_VERSION, MDMF_VERSION
20 from allmydata.blacklist import ProhibitedNode
21 from allmydata.monitor import Monitor, OperationCancelledError
22 from allmydata import dirnode
23 from allmydata.web.common import text_plain, WebError, \
24 IOpHandleTable, NeedOperationHandleError, \
25 boolean_of_arg, get_arg, get_root, parse_replace_arg, \
26 should_create_intermediate_directories, \
27 getxmlfile, RenderMixin, humanize_failure, convert_children_json, \
28 get_format, get_mutable_type
29 from allmydata.web.filenode import ReplaceMeMixin, \
30 FileNodeHandler, PlaceHolderNodeHandler
31 from allmydata.web.check_results import CheckResultsRenderer, \
32 CheckAndRepairResultsRenderer, DeepCheckResultsRenderer, \
33 DeepCheckAndRepairResultsRenderer, LiteralCheckResultsRenderer
34 from allmydata.web.info import MoreInfo
35 from allmydata.web.operations import ReloadMixin
36 from allmydata.web.check_results import json_check_results, \
37 json_check_and_repair_results
39 class BlockingFileError(Exception):
40 # TODO: catch and transform
41 """We cannot auto-create a parent directory, because there is a file in
44 def make_handler_for(node, client, parentnode=None, name=None):
46 assert IDirectoryNode.providedBy(parentnode)
47 if IFileNode.providedBy(node):
48 return FileNodeHandler(client, node, parentnode, name)
49 if IDirectoryNode.providedBy(node):
50 return DirectoryNodeHandler(client, node, parentnode, name)
51 return UnknownNodeHandler(client, node, parentnode, name)
53 class DirectoryNodeHandler(RenderMixin, rend.Page, ReplaceMeMixin):
56 def __init__(self, client, node, parentnode=None, name=None):
57 rend.Page.__init__(self)
61 self.parentnode = parentnode
64 def childFactory(self, ctx, name):
65 name = name.decode("utf-8")
67 raise EmptyPathnameComponentError()
68 d = self.node.get(name)
69 d.addBoth(self.got_child, ctx, name)
70 # got_child returns a handler resource: FileNodeHandler or
71 # DirectoryNodeHandler
74 def got_child(self, node_or_failure, ctx, name):
76 if DEBUG: print "GOT_CHILD", name, node_or_failure
79 nonterminal = len(req.postpath) > 1
80 t = get_arg(req, "t", "").strip()
81 if isinstance(node_or_failure, Failure):
83 f.trap(NoSuchChildError)
84 # No child by this name. What should we do about it?
85 if DEBUG: print "no child", name
86 if DEBUG: print "postpath", req.postpath
88 if DEBUG: print " intermediate"
89 if should_create_intermediate_directories(req):
90 # create intermediate directories
91 if DEBUG: print " making intermediate directory"
92 d = self.node.create_subdirectory(name)
93 d.addCallback(make_handler_for,
94 self.client, self.node, name)
97 if DEBUG: print " terminal"
99 if (method,t) in [ ("POST","mkdir"), ("PUT","mkdir"),
100 ("POST", "mkdir-with-children"),
101 ("POST", "mkdir-immutable") ]:
102 if DEBUG: print " making final directory"
105 if t in ("mkdir-with-children", "mkdir-immutable"):
107 kids_json = req.content.read()
108 kids = convert_children_json(self.client.nodemaker,
110 file_format = get_format(req, None)
112 mt = get_mutable_type(file_format)
113 if t == "mkdir-immutable":
116 d = self.node.create_subdirectory(name, kids,
119 d.addCallback(make_handler_for,
120 self.client, self.node, name)
122 if (method,t) in ( ("PUT",""), ("PUT","uri"), ):
123 if DEBUG: print " PUT, making leaf placeholder"
124 # we were trying to find the leaf filenode (to put a new
125 # file in its place), and it didn't exist. That's ok,
126 # since that's the leaf node that we're about to create.
127 # We make a dummy one, which will respond to the PUT
128 # request by replacing itself.
129 return PlaceHolderNodeHandler(self.client, self.node, name)
130 if DEBUG: print " 404"
131 # otherwise, we just return a no-such-child error
134 node = node_or_failure
135 if nonterminal and should_create_intermediate_directories(req):
136 if not IDirectoryNode.providedBy(node):
137 # we would have put a new directory here, but there was a
139 if DEBUG: print "blocking"
140 raise WebError("Unable to create directory '%s': "
141 "a file was in the way" % name,
143 if DEBUG: print "good child"
144 return make_handler_for(node, self.client, self.node, name)
146 def render_DELETE(self, ctx):
147 assert self.parentnode and self.name
148 d = self.parentnode.delete(self.name)
149 d.addCallback(lambda res: self.node.get_uri())
152 def render_GET(self, ctx):
154 # This is where all of the directory-related ?t=* code goes.
155 t = get_arg(req, "t", "").strip()
157 # render the directory as HTML, using the docFactory and Nevow's
158 # whole templating thing.
159 return DirectoryAsHTML(self.node,
160 self.client.mutable_file_default)
163 return DirectoryJSONMetadata(ctx, self.node)
165 return MoreInfo(self.node)
167 return DirectoryURI(ctx, self.node)
168 if t == "readonly-uri":
169 return DirectoryReadonlyURI(ctx, self.node)
170 if t == 'rename-form':
171 return RenameForm(self.node)
173 return MoveForm(self.node)
175 raise WebError("GET directory: bad t=%s" % t)
177 def render_PUT(self, ctx):
179 t = get_arg(req, "t", "").strip()
180 replace = parse_replace_arg(get_arg(req, "replace", "true"))
183 # our job was done by the traversal/create-intermediate-directory
184 # process that got us here.
185 return text_plain(self.node.get_uri(), ctx) # TODO: urlencode
188 # they're trying to set_uri and that name is already occupied
190 raise ExistingChildError()
191 d = self.replace_me_with_a_childcap(req, self.client, replace)
195 raise WebError("PUT to a directory")
197 def render_POST(self, ctx):
199 t = get_arg(req, "t", "").strip()
202 d = self._POST_mkdir(req)
203 elif t == "mkdir-with-children":
204 d = self._POST_mkdir_with_children(req)
205 elif t == "mkdir-immutable":
206 d = self._POST_mkdir_immutable(req)
209 d = self._POST_mkdir_p(req)
211 d = self._POST_upload(ctx) # this one needs the context
213 d = self._POST_uri(req)
214 elif t == "delete" or t == "unlink":
215 d = self._POST_unlink(req)
217 d = self._POST_rename(req)
219 d = self._POST_move(req)
221 d = self._POST_check(req)
222 elif t == "start-deep-check":
223 d = self._POST_start_deep_check(ctx)
224 elif t == "stream-deep-check":
225 d = self._POST_stream_deep_check(ctx)
226 elif t == "start-manifest":
227 d = self._POST_start_manifest(ctx)
228 elif t == "start-deep-size":
229 d = self._POST_start_deep_size(ctx)
230 elif t == "start-deep-stats":
231 d = self._POST_start_deep_stats(ctx)
232 elif t == "stream-manifest":
233 d = self._POST_stream_manifest(ctx)
234 elif t == "set_children" or t == "set-children":
235 d = self._POST_set_children(req)
237 raise WebError("POST to a directory with bad t=%s" % t)
239 when_done = get_arg(req, "when_done", None)
241 d.addCallback(lambda res: url.URL.fromString(when_done))
244 def _POST_mkdir(self, req):
245 name = get_arg(req, "name", "")
247 # our job is done, it was handled by the code in got_child
248 # which created the final directory (i.e. us)
249 return defer.succeed(self.node.get_uri()) # TODO: urlencode
250 name = name.decode("utf-8")
251 replace = boolean_of_arg(get_arg(req, "replace", "true"))
253 mt = get_mutable_type(get_format(req, None))
254 d = self.node.create_subdirectory(name, kids, overwrite=replace,
256 d.addCallback(lambda child: child.get_uri()) # TODO: urlencode
259 def _POST_mkdir_with_children(self, req):
260 name = get_arg(req, "name", "")
262 # our job is done, it was handled by the code in got_child
263 # which created the final directory (i.e. us)
264 return defer.succeed(self.node.get_uri()) # TODO: urlencode
265 name = name.decode("utf-8")
266 # TODO: decide on replace= behavior, see #903
267 #replace = boolean_of_arg(get_arg(req, "replace", "false"))
269 kids_json = req.content.read()
270 kids = convert_children_json(self.client.nodemaker, kids_json)
271 mt = get_mutable_type(get_format(req, None))
272 d = self.node.create_subdirectory(name, kids, overwrite=False,
274 d.addCallback(lambda child: child.get_uri()) # TODO: urlencode
277 def _POST_mkdir_immutable(self, req):
278 name = get_arg(req, "name", "")
280 # our job is done, it was handled by the code in got_child
281 # which created the final directory (i.e. us)
282 return defer.succeed(self.node.get_uri()) # TODO: urlencode
283 name = name.decode("utf-8")
284 # TODO: decide on replace= behavior, see #903
285 #replace = boolean_of_arg(get_arg(req, "replace", "false"))
287 kids_json = req.content.read()
288 kids = convert_children_json(self.client.nodemaker, kids_json)
289 d = self.node.create_subdirectory(name, kids, overwrite=False, mutable=False)
290 d.addCallback(lambda child: child.get_uri()) # TODO: urlencode
293 def _POST_mkdir_p(self, req):
294 path = get_arg(req, "path")
296 raise WebError("mkdir-p requires a path")
297 path_ = tuple([seg.decode("utf-8") for seg in path.split('/') if seg ])
299 d = self._get_or_create_directories(self.node, path_)
300 d.addCallback(lambda node: node.get_uri())
303 def _get_or_create_directories(self, node, path):
304 if not IDirectoryNode.providedBy(node):
305 # unfortunately it is too late to provide the name of the
306 # blocking directory in the error message.
307 raise BlockingFileError("cannot create directory because there "
308 "is a file in the way")
310 return defer.succeed(node)
311 d = node.get(path[0])
312 def _maybe_create(f):
313 f.trap(NoSuchChildError)
314 return node.create_subdirectory(path[0])
315 d.addErrback(_maybe_create)
316 d.addCallback(self._get_or_create_directories, path[1:])
319 def _POST_upload(self, ctx):
321 charset = get_arg(req, "_charset", "utf-8")
322 contents = req.fields["file"]
323 assert contents.filename is None or isinstance(contents.filename, str)
324 name = get_arg(req, "name")
325 name = name or contents.filename
329 # this prohibts empty, missing, and all-whitespace filenames
330 raise WebError("upload requires a name")
331 assert isinstance(name, str)
332 name = name.decode(charset)
334 raise WebError("name= may not contain a slash", http.BAD_REQUEST)
335 assert isinstance(name, unicode)
337 # since POST /uri/path/file?t=upload is equivalent to
338 # POST /uri/path/dir?t=upload&name=foo, just do the same thing that
339 # childFactory would do. Things are cleaner if we only do a subset of
340 # them, though, so we don't do: d = self.childFactory(ctx, name)
342 d = self.node.get(name)
343 def _maybe_got_node(node_or_failure):
344 if isinstance(node_or_failure, Failure):
346 f.trap(NoSuchChildError)
347 # create a placeholder which will see POST t=upload
348 return PlaceHolderNodeHandler(self.client, self.node, name)
350 node = node_or_failure
351 return make_handler_for(node, self.client, self.node, name)
352 d.addBoth(_maybe_got_node)
353 # now we have a placeholder or a filenodehandler, and we can just
354 # delegate to it. We could return the resource back out of
355 # DirectoryNodeHandler.renderHTTP, and nevow would recurse into it,
356 # but the addCallback() that handles when_done= would break.
357 d.addCallback(lambda child: child.renderHTTP(ctx))
360 def _POST_uri(self, req):
361 childcap = get_arg(req, "uri")
363 raise WebError("set-uri requires a uri")
364 name = get_arg(req, "name")
366 raise WebError("set-uri requires a name")
367 charset = get_arg(req, "_charset", "utf-8")
368 name = name.decode(charset)
369 replace = boolean_of_arg(get_arg(req, "replace", "true"))
371 # We mustn't pass childcap for the readcap argument because we don't
372 # know whether it is a read cap. Passing a read cap as the writecap
373 # argument will work (it ends up calling NodeMaker.create_from_cap,
374 # which derives a readcap if necessary and possible).
375 d = self.node.set_uri(name, childcap, None, overwrite=replace)
376 d.addCallback(lambda res: childcap)
379 def _POST_unlink(self, req):
380 name = get_arg(req, "name")
382 # apparently an <input type="hidden" name="name" value="">
383 # won't show up in the resulting encoded form.. the 'name'
384 # field is completely missing. So to allow unlinking of a
385 # child with a name that is the empty string, we have to
386 # pretend that None means ''. The only downside of this is
387 # a slightly confusing error message if someone does a POST
388 # without a name= field. For our own HTML this isn't a big
389 # deal, because we create the 'unlink' POST buttons ourselves.
391 charset = get_arg(req, "_charset", "utf-8")
392 name = name.decode(charset)
393 d = self.node.delete(name)
394 d.addCallback(lambda res: "thing unlinked")
397 def _POST_rename(self, req):
398 charset = get_arg(req, "_charset", "utf-8")
399 from_name = get_arg(req, "from_name")
400 if from_name is not None:
401 from_name = from_name.strip()
402 from_name = from_name.decode(charset)
403 assert isinstance(from_name, unicode)
404 to_name = get_arg(req, "to_name")
405 if to_name is not None:
406 to_name = to_name.strip()
407 to_name = to_name.decode(charset)
408 assert isinstance(to_name, unicode)
409 if not from_name or not to_name:
410 raise WebError("rename requires from_name and to_name")
411 if from_name == to_name:
412 return defer.succeed("redundant rename")
414 # allow from_name to contain slashes, so they can fix names that were
415 # accidentally created with them. But disallow them in to_name, to
416 # discourage the practice.
418 raise WebError("to_name= may not contain a slash", http.BAD_REQUEST)
420 replace = boolean_of_arg(get_arg(req, "replace", "true"))
421 d = self.node.move_child_to(from_name, self.node, to_name, replace)
422 d.addCallback(lambda res: "thing renamed")
425 def _POST_move(self, req):
426 charset = get_arg(req, "_charset", "utf-8")
427 from_name = get_arg(req, "from_name")
428 if from_name is not None:
429 from_name = from_name.strip()
430 from_name = from_name.decode(charset)
431 assert isinstance(from_name, unicode)
432 to_name = get_arg(req, "to_name")
433 if to_name is not None:
434 to_name = to_name.strip()
435 to_name = to_name.decode(charset)
436 assert isinstance(to_name, unicode)
439 to_dir = get_arg(req, "to_dir")
440 if to_dir is not None:
441 to_dir = to_dir.strip()
442 to_dir = to_dir.decode(charset)
443 assert isinstance(to_dir, unicode)
444 if not from_name or not to_dir:
445 raise WebError("move requires from_name and to_dir")
446 replace = boolean_of_arg(get_arg(req, "replace", "true"))
447 target_type = get_arg(req, "target_type", "name")
448 if not target_type in ["name", "uri"]:
449 raise WebError("invalid target_type parameter",
452 # allow from_name to contain slashes, so they can fix names that
453 # were accidentally created with them. But disallow them in to_name
454 # (if it's specified), to discourage the practice.
455 if to_name and "/" in to_name:
456 raise WebError("to_name= may not contain a slash",
460 def get_target_node(target_type):
461 if target_type == "name":
462 return self.node.get_child_at_path(to_dir)
463 elif target_type == "uri":
464 return self.client.create_node_from_uri(str(to_dir))
465 d.addCallback(get_target_node)
466 d.callback(target_type)
467 def is_target_node_usable(target_node):
468 if not IDirectoryNode.providedBy(target_node):
469 raise WebError("to_dir is not a usable directory",
472 d.addCallback(is_target_node_usable)
473 d.addCallback(lambda new_parent: self.node.move_child_to(
474 from_name, new_parent, to_name, replace))
475 d.addCallback(lambda res: "thing moved")
478 def _maybe_literal(self, res, Results_Class):
480 return Results_Class(self.client, res)
481 return LiteralCheckResultsRenderer(self.client)
483 def _POST_check(self, req):
484 # check this directory
485 verify = boolean_of_arg(get_arg(req, "verify", "false"))
486 repair = boolean_of_arg(get_arg(req, "repair", "false"))
487 add_lease = boolean_of_arg(get_arg(req, "add-lease", "false"))
489 d = self.node.check_and_repair(Monitor(), verify, add_lease)
490 d.addCallback(self._maybe_literal, CheckAndRepairResultsRenderer)
492 d = self.node.check(Monitor(), verify, add_lease)
493 d.addCallback(self._maybe_literal, CheckResultsRenderer)
496 def _start_operation(self, monitor, renderer, ctx):
497 table = IOpHandleTable(ctx)
498 table.add_monitor(ctx, monitor, renderer)
499 return table.redirect_to(ctx)
501 def _POST_start_deep_check(self, ctx):
502 # check this directory and everything reachable from it
503 if not get_arg(ctx, "ophandle"):
504 raise NeedOperationHandleError("slow operation requires ophandle=")
505 verify = boolean_of_arg(get_arg(ctx, "verify", "false"))
506 repair = boolean_of_arg(get_arg(ctx, "repair", "false"))
507 add_lease = boolean_of_arg(get_arg(ctx, "add-lease", "false"))
509 monitor = self.node.start_deep_check_and_repair(verify, add_lease)
510 renderer = DeepCheckAndRepairResultsRenderer(self.client, monitor)
512 monitor = self.node.start_deep_check(verify, add_lease)
513 renderer = DeepCheckResultsRenderer(self.client, monitor)
514 return self._start_operation(monitor, renderer, ctx)
516 def _POST_stream_deep_check(self, ctx):
517 verify = boolean_of_arg(get_arg(ctx, "verify", "false"))
518 repair = boolean_of_arg(get_arg(ctx, "repair", "false"))
519 add_lease = boolean_of_arg(get_arg(ctx, "add-lease", "false"))
520 walker = DeepCheckStreamer(ctx, self.node, verify, repair, add_lease)
521 monitor = self.node.deep_traverse(walker)
522 walker.setMonitor(monitor)
523 # register to hear stopProducing. The walker ignores pauseProducing.
524 IRequest(ctx).registerProducer(walker, True)
525 d = monitor.when_done()
527 IRequest(ctx).unregisterProducer()
531 f.trap(OperationCancelledError)
532 return "Operation Cancelled"
533 d.addErrback(_cancelled)
535 # signal the error as a non-JSON "ERROR:" line, plus exception
536 msg = "ERROR: %s(%s)\n" % (f.value.__class__.__name__,
537 ", ".join([str(a) for a in f.value.args]))
543 def _POST_start_manifest(self, ctx):
544 if not get_arg(ctx, "ophandle"):
545 raise NeedOperationHandleError("slow operation requires ophandle=")
546 monitor = self.node.build_manifest()
547 renderer = ManifestResults(self.client, monitor)
548 return self._start_operation(monitor, renderer, ctx)
550 def _POST_start_deep_size(self, ctx):
551 if not get_arg(ctx, "ophandle"):
552 raise NeedOperationHandleError("slow operation requires ophandle=")
553 monitor = self.node.start_deep_stats()
554 renderer = DeepSizeResults(self.client, monitor)
555 return self._start_operation(monitor, renderer, ctx)
557 def _POST_start_deep_stats(self, ctx):
558 if not get_arg(ctx, "ophandle"):
559 raise NeedOperationHandleError("slow operation requires ophandle=")
560 monitor = self.node.start_deep_stats()
561 renderer = DeepStatsResults(self.client, monitor)
562 return self._start_operation(monitor, renderer, ctx)
564 def _POST_stream_manifest(self, ctx):
565 walker = ManifestStreamer(ctx, self.node)
566 monitor = self.node.deep_traverse(walker)
567 walker.setMonitor(monitor)
568 # register to hear stopProducing. The walker ignores pauseProducing.
569 IRequest(ctx).registerProducer(walker, True)
570 d = monitor.when_done()
572 IRequest(ctx).unregisterProducer()
576 f.trap(OperationCancelledError)
577 return "Operation Cancelled"
578 d.addErrback(_cancelled)
580 # signal the error as a non-JSON "ERROR:" line, plus exception
581 msg = "ERROR: %s(%s)\n" % (f.value.__class__.__name__,
582 ", ".join([str(a) for a in f.value.args]))
588 def _POST_set_children(self, req):
589 replace = boolean_of_arg(get_arg(req, "replace", "true"))
591 body = req.content.read()
593 children = simplejson.loads(body)
594 except ValueError, le:
595 le.args = tuple(le.args + (body,))
596 # TODO test handling of bad JSON
599 for name, (file_or_dir, mddict) in children.iteritems():
600 name = unicode(name) # simplejson-2.0.1 returns str *or* unicode
601 writecap = mddict.get('rw_uri')
602 if writecap is not None:
603 writecap = str(writecap)
604 readcap = mddict.get('ro_uri')
605 if readcap is not None:
606 readcap = str(readcap)
607 cs[name] = (writecap, readcap, mddict.get('metadata'))
608 d = self.node.set_children(cs, replace)
609 d.addCallback(lambda res: "Okay so I did it.")
613 def abbreviated_dirnode(dirnode):
614 u = from_string_dirnode(dirnode.get_uri())
619 class DirectoryAsHTML(rend.Page):
620 # The remainder of this class is to render the directory into
621 # human+browser -oriented HTML.
622 docFactory = getxmlfile("directory.xhtml")
625 def __init__(self, node, default_mutable_format):
626 rend.Page.__init__(self)
629 assert default_mutable_format in (MDMF_VERSION, SDMF_VERSION)
630 self.default_mutable_format = default_mutable_format
632 def beforeRender(self, ctx):
633 # attempt to get the dirnode's children, stashing them (or the
634 # failure that results) for later use
637 # Deferreds don't optimize out tail recursion, and the way
638 # Nevow's flattener handles Deferreds doesn't take this into
639 # account. As a result, large lists of Deferreds that fire in the
640 # same turn (i.e. the output of defer.succeed) will cause a stack
641 # overflow. To work around this, we insert a turn break after
642 # every 100 items, using foolscap's fireEventually(). This gives
643 # the stack a chance to be popped. It would also work to put
644 # every item in its own turn, but that'd be a lot more
645 # inefficient. This addresses ticket #237, for which I was never
646 # able to create a failing unit test.
648 for i,item in enumerate(sorted(children.items())):
650 output.append(fireEventually(item))
653 self.dirnode_children = output
656 text, code = humanize_failure(f)
657 self.dirnode_children = None
658 self.dirnode_children_error = text
660 d.addCallbacks(_good, _bad)
663 def render_title(self, ctx, data):
664 si_s = abbreviated_dirnode(self.node)
665 header = ["Tahoe-LAFS - Directory SI=%s" % si_s]
666 if self.node.is_unknown():
667 header.append(" (unknown)")
668 elif not self.node.is_mutable():
669 header.append(" (immutable)")
670 elif self.node.is_readonly():
671 header.append(" (read-only)")
673 header.append(" (modifiable)")
674 return ctx.tag[header]
676 def render_header(self, ctx, data):
677 si_s = abbreviated_dirnode(self.node)
678 header = ["Tahoe-LAFS Directory SI=", T.span(class_="data-chars")[si_s]]
679 if self.node.is_unknown():
680 header.append(" (unknown)")
681 elif not self.node.is_mutable():
682 header.append(" (immutable)")
683 elif self.node.is_readonly():
684 header.append(" (read-only)")
685 return ctx.tag[header]
687 def render_welcome(self, ctx, data):
689 return ctx.tag[T.a(href=link)["Return to Welcome page"]]
691 def render_show_readonly(self, ctx, data):
692 if self.node.is_unknown() or self.node.is_readonly():
694 rocap = self.node.get_readonly_uri()
696 uri_link = "%s/uri/%s/" % (root, urllib.quote(rocap))
697 return ctx.tag[T.a(href=uri_link)["Read-Only Version"]]
699 def render_try_children(self, ctx, data):
700 # if the dirnode can be retrived, render a table of children.
701 # Otherwise, render an apologetic error message.
702 if self.dirnode_children is not None:
705 return T.div[T.p["Error reading directory:"],
706 T.p[self.dirnode_children_error]]
708 def data_children(self, ctx, data):
709 return self.dirnode_children
711 def render_row(self, ctx, data):
712 name, (target, metadata) = data
713 name = name.encode("utf-8")
714 assert not isinstance(name, unicode)
715 nameurl = urllib.quote(name, safe="") # encode any slashes too
718 here = "%s/uri/%s/" % (root, urllib.quote(self.node.get_uri()))
719 if self.node.is_unknown() or self.node.is_readonly():
724 # this creates a button which will cause our _POST_unlink method
725 # to be invoked, which unlinks the file and then redirects the
726 # browser back to this directory
727 unlink = T.form(action=here, method="post")[
728 T.input(type='hidden', name='t', value='unlink'),
729 T.input(type='hidden', name='name', value=name),
730 T.input(type='hidden', name='when_done', value="."),
731 T.input(type='submit', value='unlink', name="unlink"),
734 rename = T.form(action=here, method="get")[
735 T.input(type='hidden', name='t', value='rename-form'),
736 T.input(type='hidden', name='name', value=name),
737 T.input(type='hidden', name='when_done', value="."),
738 T.input(type='submit', value='rename', name="rename"),
741 move = T.form(action=here, method="get")[
742 T.input(type='hidden', name='t', value='move-form'),
743 T.input(type='hidden', name='name', value=name),
744 T.input(type='hidden', name='when_done', value="."),
745 T.input(type='submit', value='move', name="move"),
748 ctx.fillSlots("unlink", unlink)
749 ctx.fillSlots("rename", rename)
750 ctx.fillSlots("move", move)
753 linkcrtime = metadata.get('tahoe', {}).get("linkcrtime")
754 if linkcrtime is not None:
755 times.append("lcr: " + time_format.iso_local(linkcrtime))
757 # For backwards-compatibility with links last modified by Tahoe < 1.4.0:
758 if "ctime" in metadata:
759 ctime = time_format.iso_local(metadata["ctime"])
760 times.append("c: " + ctime)
761 linkmotime = metadata.get('tahoe', {}).get("linkmotime")
762 if linkmotime is not None:
765 times.append("lmo: " + time_format.iso_local(linkmotime))
767 # For backwards-compatibility with links last modified by Tahoe < 1.4.0:
768 if "mtime" in metadata:
769 mtime = time_format.iso_local(metadata["mtime"])
772 times.append("m: " + mtime)
773 ctx.fillSlots("times", times)
775 assert IFilesystemNode.providedBy(target), target
776 target_uri = target.get_uri() or ""
777 quoted_uri = urllib.quote(target_uri, safe="") # escape slashes too
779 if IMutableFileNode.providedBy(target):
780 # to prevent javascript in displayed .html files from stealing a
781 # secret directory URI from the URL, send the browser to a URI-based
782 # page that doesn't know about the directory at all
783 dlurl = "%s/file/%s/@@named=/%s" % (root, quoted_uri, nameurl)
785 ctx.fillSlots("filename",
786 T.a(href=dlurl)[html.escape(name)])
787 ctx.fillSlots("type", "SSK")
789 ctx.fillSlots("size", "?")
791 info_link = "%s/uri/%s?t=info" % (root, quoted_uri)
793 elif IImmutableFileNode.providedBy(target):
794 dlurl = "%s/file/%s/@@named=/%s" % (root, quoted_uri, nameurl)
796 ctx.fillSlots("filename",
797 T.a(href=dlurl)[html.escape(name)])
798 ctx.fillSlots("type", "FILE")
800 ctx.fillSlots("size", target.get_size())
802 info_link = "%s/uri/%s?t=info" % (root, quoted_uri)
804 elif IDirectoryNode.providedBy(target):
806 uri_link = "%s/uri/%s/" % (root, urllib.quote(target_uri))
807 ctx.fillSlots("filename",
808 T.a(href=uri_link)[html.escape(name)])
809 if not target.is_mutable():
811 elif target.is_readonly():
815 ctx.fillSlots("type", dirtype)
816 ctx.fillSlots("size", "-")
817 info_link = "%s/uri/%s/?t=info" % (root, quoted_uri)
819 elif isinstance(target, ProhibitedNode):
820 ctx.fillSlots("filename", T.strike[name])
821 if IDirectoryNode.providedBy(target.wrapped_node):
822 blacklisted_type = "DIR-BLACKLISTED"
824 blacklisted_type = "BLACKLISTED"
825 ctx.fillSlots("type", blacklisted_type)
826 ctx.fillSlots("size", "-")
828 ctx.fillSlots("info", ["Access Prohibited:", T.br, target.reason])
832 ctx.fillSlots("filename", html.escape(name))
833 if target.get_write_uri() is not None:
835 elif not self.node.is_mutable() or target.is_alleged_immutable():
836 unknowntype = "?-IMM"
839 ctx.fillSlots("type", unknowntype)
840 ctx.fillSlots("size", "-")
841 # use a directory-relative info link, so we can extract both the
842 # writecap and the readcap
843 info_link = "%s?t=info" % urllib.quote(name)
846 ctx.fillSlots("info", T.a(href=info_link)["More Info"])
850 # XXX: similar to render_upload_form and render_mkdir_form in root.py.
851 def render_forms(self, ctx, data):
854 if self.node.is_readonly():
855 return T.div["No upload forms: directory is read-only"]
856 if self.dirnode_children is None:
857 return T.div["No upload forms: directory is unreadable"]
859 mkdir_sdmf = T.input(type='radio', name='format',
860 value='sdmf', id='mkdir-sdmf',
862 mkdir_mdmf = T.input(type='radio', name='format',
863 value='mdmf', id='mkdir-mdmf')
865 mkdir_form = T.form(action=".", method="post",
866 enctype="multipart/form-data")[
868 T.input(type="hidden", name="t", value="mkdir"),
869 T.input(type="hidden", name="when_done", value="."),
870 T.legend(class_="freeform-form-label")["Create a new directory in this directory"],
871 "New directory name:"+SPACE,
872 T.input(type="text", name="name"), SPACE,
873 T.input(type="submit", value="Create"), SPACE*2,
874 mkdir_sdmf, T.label(for_='mutable-directory-sdmf')[" SDMF"], SPACE,
875 mkdir_mdmf, T.label(for_='mutable-directory-mdmf')[" MDMF (experimental)"],
877 forms.append(T.div(class_="freeform-form")[mkdir_form])
879 upload_chk = T.input(type='radio', name='format',
880 value='chk', id='upload-chk',
882 upload_sdmf = T.input(type='radio', name='format',
883 value='sdmf', id='upload-sdmf')
884 upload_mdmf = T.input(type='radio', name='format',
885 value='mdmf', id='upload-mdmf')
887 upload_form = T.form(action=".", method="post",
888 enctype="multipart/form-data")[
890 T.input(type="hidden", name="t", value="upload"),
891 T.input(type="hidden", name="when_done", value="."),
892 T.legend(class_="freeform-form-label")["Upload a file to this directory"],
893 "Choose a file to upload:"+SPACE,
894 T.input(type="file", name="file", class_="freeform-input-file"), SPACE,
895 T.input(type="submit", value="Upload"), SPACE*2,
896 upload_chk, T.label(for_="upload-chk") [" Immutable"], SPACE,
897 upload_sdmf, T.label(for_="upload-sdmf")[" SDMF"], SPACE,
898 upload_mdmf, T.label(for_="upload-mdmf")[" MDMF (experimental)"],
900 forms.append(T.div(class_="freeform-form")[upload_form])
902 attach_form = T.form(action=".", method="post",
903 enctype="multipart/form-data")[
905 T.input(type="hidden", name="t", value="uri"),
906 T.input(type="hidden", name="when_done", value="."),
907 T.legend(class_="freeform-form-label")["Add a link to a file or directory which is already in Tahoe-LAFS."],
908 "New child name:"+SPACE,
909 T.input(type="text", name="name"), SPACE*2,
910 "URI of new child:"+SPACE,
911 T.input(type="text", name="uri"), SPACE,
912 T.input(type="submit", value="Attach"),
914 forms.append(T.div(class_="freeform-form")[attach_form])
917 def render_results(self, ctx, data):
919 return get_arg(req, "results", "")
922 def DirectoryJSONMetadata(ctx, dirnode):
926 for name, (childnode, metadata) in children.iteritems():
927 assert IFilesystemNode.providedBy(childnode), childnode
928 rw_uri = childnode.get_write_uri()
929 ro_uri = childnode.get_readonly_uri()
930 if IFileNode.providedBy(childnode):
931 kiddata = ("filenode", {'size': childnode.get_size(),
932 'mutable': childnode.is_mutable(),
934 if childnode.is_mutable():
935 mutable_type = childnode.get_version()
936 assert mutable_type in (SDMF_VERSION, MDMF_VERSION)
937 if mutable_type == MDMF_VERSION:
943 kiddata[1]['format'] = file_format
945 elif IDirectoryNode.providedBy(childnode):
946 kiddata = ("dirnode", {'mutable': childnode.is_mutable()})
948 kiddata = ("unknown", {})
950 kiddata[1]["metadata"] = metadata
952 kiddata[1]["rw_uri"] = rw_uri
954 kiddata[1]["ro_uri"] = ro_uri
955 verifycap = childnode.get_verify_cap()
957 kiddata[1]['verify_uri'] = verifycap.to_string()
961 drw_uri = dirnode.get_write_uri()
962 dro_uri = dirnode.get_readonly_uri()
963 contents = { 'children': kids }
965 contents['ro_uri'] = dro_uri
967 contents['rw_uri'] = drw_uri
968 verifycap = dirnode.get_verify_cap()
970 contents['verify_uri'] = verifycap.to_string()
971 contents['mutable'] = dirnode.is_mutable()
972 data = ("dirnode", contents)
973 json = simplejson.dumps(data, indent=1) + "\n"
976 d.addCallback(text_plain, ctx)
980 def DirectoryURI(ctx, dirnode):
981 return text_plain(dirnode.get_uri(), ctx)
983 def DirectoryReadonlyURI(ctx, dirnode):
984 return text_plain(dirnode.get_readonly_uri(), ctx)
986 class RenameForm(rend.Page):
988 docFactory = getxmlfile("rename-form.xhtml")
990 def render_title(self, ctx, data):
991 return ctx.tag["Directory SI=%s" % abbreviated_dirnode(self.original)]
993 def render_header(self, ctx, data):
995 "in directory SI=%s" % abbreviated_dirnode(self.original),
998 if self.original.is_readonly():
999 header.append(" (readonly!)")
1001 return ctx.tag[header]
1003 def render_when_done(self, ctx, data):
1004 return T.input(type="hidden", name="when_done", value=".")
1006 def render_get_name(self, ctx, data):
1008 name = get_arg(req, "name", "")
1009 ctx.tag.attributes['value'] = name
1012 class MoveForm(rend.Page):
1014 docFactory = getxmlfile("move-form.xhtml")
1016 def render_title(self, ctx, data):
1017 return ctx.tag["Directory SI=%s" % abbreviated_dirnode(self.original)]
1019 def render_header(self, ctx, data):
1021 "from directory SI=%s" % abbreviated_dirnode(self.original),
1024 if self.original.is_readonly():
1025 header.append(" (readonly!)")
1027 return ctx.tag[header]
1029 def render_when_done(self, ctx, data):
1030 return T.input(type="hidden", name="when_done", value=".")
1032 def render_get_name(self, ctx, data):
1034 name = get_arg(req, "name", "")
1035 ctx.tag.attributes['value'] = name
1039 class ManifestResults(rend.Page, ReloadMixin):
1040 docFactory = getxmlfile("manifest.xhtml")
1042 def __init__(self, client, monitor):
1043 self.client = client
1044 self.monitor = monitor
1046 def renderHTTP(self, ctx):
1047 req = inevow.IRequest(ctx)
1048 output = get_arg(req, "output", "html").lower()
1049 if output == "text":
1050 return self.text(req)
1051 if output == "json":
1052 return self.json(req)
1053 return rend.Page.renderHTTP(self, ctx)
1055 def slashify_path(self, path):
1058 return "/".join([p.encode("utf-8") for p in path])
1060 def text(self, req):
1061 req.setHeader("content-type", "text/plain")
1063 is_finished = self.monitor.is_finished()
1064 lines.append("finished: " + {True: "yes", False: "no"}[is_finished])
1065 for (path, cap) in self.monitor.get_status()["manifest"]:
1066 lines.append(self.slashify_path(path) + " " + cap)
1067 return "\n".join(lines) + "\n"
1069 def json(self, req):
1070 req.setHeader("content-type", "text/plain")
1075 origin_base32 = base32.b2a(m.origin_si)
1078 status = { "stats": s["stats"],
1079 "finished": m.is_finished(),
1080 "origin": origin_base32,
1083 # don't return manifest/verifycaps/SIs unless the operation is
1084 # done, to save on CPU/memory (both here and in the HTTP client
1085 # who has to unpack the JSON). Tests show that the ManifestWalker
1086 # needs about 1092 bytes per item, the JSON we generate here
1087 # requires about 503 bytes per item, and some internal overhead
1088 # (perhaps transport-layer buffers in twisted.web?) requires an
1089 # additional 1047 bytes per item.
1090 status.update({ "manifest": s["manifest"],
1091 "verifycaps": [i for i in s["verifycaps"]],
1092 "storage-index": [i for i in s["storage-index"]],
1094 # simplejson doesn't know how to serialize a set. We use a
1095 # generator that walks the set rather than list(setofthing) to
1096 # save a small amount of memory (4B*len) and a moderate amount of
1098 return simplejson.dumps(status, indent=1)
1100 def _si_abbrev(self):
1101 si = self.monitor.origin_si
1104 return base32.b2a(si)[:6]
1106 def render_title(self, ctx):
1107 return T.title["Manifest of SI=%s" % self._si_abbrev()]
1109 def render_header(self, ctx):
1110 return T.p["Manifest of SI=%s" % self._si_abbrev()]
1112 def data_items(self, ctx, data):
1113 return self.monitor.get_status()["manifest"]
1115 def render_row(self, ctx, (path, cap)):
1116 ctx.fillSlots("path", self.slashify_path(path))
1117 root = get_root(ctx)
1118 # TODO: we need a clean consistent way to get the type of a cap string
1120 if cap.startswith("URI:CHK") or cap.startswith("URI:SSK"):
1121 nameurl = urllib.quote(path[-1].encode("utf-8"))
1122 uri_link = "%s/file/%s/@@named=/%s" % (root, urllib.quote(cap),
1125 uri_link = "%s/uri/%s" % (root, urllib.quote(cap, safe=""))
1126 ctx.fillSlots("cap", T.a(href=uri_link)[cap])
1128 ctx.fillSlots("cap", "")
1131 class DeepSizeResults(rend.Page):
1132 def __init__(self, client, monitor):
1133 self.client = client
1134 self.monitor = monitor
1136 def renderHTTP(self, ctx):
1137 req = inevow.IRequest(ctx)
1138 output = get_arg(req, "output", "html").lower()
1139 req.setHeader("content-type", "text/plain")
1140 if output == "json":
1141 return self.json(req)
1143 is_finished = self.monitor.is_finished()
1144 output = "finished: " + {True: "yes", False: "no"}[is_finished] + "\n"
1146 stats = self.monitor.get_status()
1147 total = (stats.get("size-immutable-files", 0)
1148 + stats.get("size-mutable-files", 0)
1149 + stats.get("size-directories", 0))
1150 output += "size: %d\n" % total
1153 def json(self, req):
1154 status = {"finished": self.monitor.is_finished(),
1155 "size": self.monitor.get_status(),
1157 return simplejson.dumps(status)
1159 class DeepStatsResults(rend.Page):
1160 def __init__(self, client, monitor):
1161 self.client = client
1162 self.monitor = monitor
1164 def renderHTTP(self, ctx):
1166 inevow.IRequest(ctx).setHeader("content-type", "text/plain")
1167 s = self.monitor.get_status().copy()
1168 s["finished"] = self.monitor.is_finished()
1169 return simplejson.dumps(s, indent=1)
1171 class ManifestStreamer(dirnode.DeepStats):
1172 implements(IPushProducer)
1174 def __init__(self, ctx, origin):
1175 dirnode.DeepStats.__init__(self, origin)
1176 self.req = IRequest(ctx)
1178 def setMonitor(self, monitor):
1179 self.monitor = monitor
1180 def pauseProducing(self):
1182 def resumeProducing(self):
1184 def stopProducing(self):
1185 self.monitor.cancel()
1187 def add_node(self, node, path):
1188 dirnode.DeepStats.add_node(self, node, path)
1190 "cap": node.get_uri()}
1192 if IDirectoryNode.providedBy(node):
1193 d["type"] = "directory"
1194 elif IFileNode.providedBy(node):
1197 d["type"] = "unknown"
1199 v = node.get_verify_cap()
1202 d["verifycap"] = v or ""
1204 r = node.get_repair_cap()
1207 d["repaircap"] = r or ""
1209 si = node.get_storage_index()
1212 d["storage-index"] = si or ""
1214 j = simplejson.dumps(d, ensure_ascii=True)
1215 assert "\n" not in j
1216 self.req.write(j+"\n")
1219 stats = dirnode.DeepStats.get_results(self)
1220 d = {"type": "stats",
1223 j = simplejson.dumps(d, ensure_ascii=True)
1224 assert "\n" not in j
1225 self.req.write(j+"\n")
1228 class DeepCheckStreamer(dirnode.DeepStats):
1229 implements(IPushProducer)
1231 def __init__(self, ctx, origin, verify, repair, add_lease):
1232 dirnode.DeepStats.__init__(self, origin)
1233 self.req = IRequest(ctx)
1234 self.verify = verify
1235 self.repair = repair
1236 self.add_lease = add_lease
1238 def setMonitor(self, monitor):
1239 self.monitor = monitor
1240 def pauseProducing(self):
1242 def resumeProducing(self):
1244 def stopProducing(self):
1245 self.monitor.cancel()
1247 def add_node(self, node, path):
1248 dirnode.DeepStats.add_node(self, node, path)
1249 data = {"path": path,
1250 "cap": node.get_uri()}
1252 if IDirectoryNode.providedBy(node):
1253 data["type"] = "directory"
1254 elif IFileNode.providedBy(node):
1255 data["type"] = "file"
1257 data["type"] = "unknown"
1259 v = node.get_verify_cap()
1262 data["verifycap"] = v or ""
1264 r = node.get_repair_cap()
1267 data["repaircap"] = r or ""
1269 si = node.get_storage_index()
1272 data["storage-index"] = si or ""
1275 d = node.check_and_repair(self.monitor, self.verify, self.add_lease)
1276 d.addCallback(self.add_check_and_repair, data)
1278 d = node.check(self.monitor, self.verify, self.add_lease)
1279 d.addCallback(self.add_check, data)
1280 d.addCallback(self.write_line)
1283 def add_check_and_repair(self, crr, data):
1284 data["check-and-repair-results"] = json_check_and_repair_results(crr)
1287 def add_check(self, cr, data):
1288 data["check-results"] = json_check_results(cr)
1291 def write_line(self, data):
1292 j = simplejson.dumps(data, ensure_ascii=True)
1293 assert "\n" not in j
1294 self.req.write(j+"\n")
1297 stats = dirnode.DeepStats.get_results(self)
1298 d = {"type": "stats",
1301 j = simplejson.dumps(d, ensure_ascii=True)
1302 assert "\n" not in j
1303 self.req.write(j+"\n")
1307 class UnknownNodeHandler(RenderMixin, rend.Page):
1308 def __init__(self, client, node, parentnode=None, name=None):
1309 rend.Page.__init__(self)
1312 self.parentnode = parentnode
1315 def render_GET(self, ctx):
1317 t = get_arg(req, "t", "").strip()
1319 return MoreInfo(self.node)
1321 is_parent_known_immutable = self.parentnode and not self.parentnode.is_mutable()
1322 if self.parentnode and self.name:
1323 d = self.parentnode.get_metadata_for(self.name)
1325 d = defer.succeed(None)
1326 d.addCallback(lambda md: UnknownJSONMetadata(ctx, self.node, md, is_parent_known_immutable))
1328 raise WebError("GET unknown URI type: can only do t=info and t=json, not t=%s.\n"
1329 "Using a webapi server that supports a later version of Tahoe "
1332 def UnknownJSONMetadata(ctx, node, edge_metadata, is_parent_known_immutable):
1333 rw_uri = node.get_write_uri()
1334 ro_uri = node.get_readonly_uri()
1335 data = ("unknown", {})
1337 data[1]['ro_uri'] = ro_uri
1339 data[1]['rw_uri'] = rw_uri
1340 data[1]['mutable'] = True
1341 elif is_parent_known_immutable or node.is_alleged_immutable():
1342 data[1]['mutable'] = False
1343 # else we don't know whether it is mutable.
1345 if edge_metadata is not None:
1346 data[1]['metadata'] = edge_metadata
1347 return text_plain(simplejson.dumps(data, indent=1) + "\n", ctx)