]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/directory.py
src/allmydata/web/directory.py: fix HTML double-encoding issue for filenames.
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / web / directory.py
1
2 import simplejson
3 import urllib
4
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
10 from nevow import url, rend, inevow, tags as T
11 from nevow.inevow import IRequest
12
13 from foolscap.api import fireEventually
14
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
38
39 class BlockingFileError(Exception):
40     # TODO: catch and transform
41     """We cannot auto-create a parent directory, because there is a file in
42     the way"""
43
44 def make_handler_for(node, client, parentnode=None, name=None):
45     if parentnode:
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)
52
53 class DirectoryNodeHandler(RenderMixin, rend.Page, ReplaceMeMixin):
54     addSlash = True
55
56     def __init__(self, client, node, parentnode=None, name=None):
57         rend.Page.__init__(self)
58         self.client = client
59         assert node
60         self.node = node
61         self.parentnode = parentnode
62         self.name = name
63
64     def childFactory(self, ctx, name):
65         name = name.decode("utf-8")
66         if not name:
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
72         return d
73
74     def got_child(self, node_or_failure, ctx, name):
75         DEBUG = False
76         if DEBUG: print "GOT_CHILD", name, node_or_failure
77         req = IRequest(ctx)
78         method = req.method
79         nonterminal = len(req.postpath) > 1
80         t = get_arg(req, "t", "").strip()
81         if isinstance(node_or_failure, Failure):
82             f = node_or_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
87             if nonterminal:
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)
95                     return d
96             else:
97                 if DEBUG: print " terminal"
98                 # terminal node
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"
103                     # final directory
104                     kids = {}
105                     if t in ("mkdir-with-children", "mkdir-immutable"):
106                         req.content.seek(0)
107                         kids_json = req.content.read()
108                         kids = convert_children_json(self.client.nodemaker,
109                                                      kids_json)
110                     file_format = get_format(req, None)
111                     mutable = True
112                     mt = get_mutable_type(file_format)
113                     if t == "mkdir-immutable":
114                         mutable = False
115
116                     d = self.node.create_subdirectory(name, kids,
117                                                       mutable=mutable,
118                                                       mutable_version=mt)
119                     d.addCallback(make_handler_for,
120                                   self.client, self.node, name)
121                     return d
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
132             return f
133
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
138                 # file in the way.
139                 if DEBUG: print "blocking"
140                 raise WebError("Unable to create directory '%s': "
141                                "a file was in the way" % name,
142                                http.CONFLICT)
143         if DEBUG: print "good child"
144         return make_handler_for(node, self.client, self.node, name)
145
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())
150         return d
151
152     def render_GET(self, ctx):
153         req = IRequest(ctx)
154         # This is where all of the directory-related ?t=* code goes.
155         t = get_arg(req, "t", "").strip()
156
157         # t=info contains variable ophandles, t=rename-form contains the name
158         # of the child being renamed. Neither is allowed an ETag.
159         FIXED_OUTPUT_TYPES =  ["", "json", "uri", "readonly-uri"]
160         if not self.node.is_mutable() and t in FIXED_OUTPUT_TYPES:
161             si = self.node.get_storage_index()
162             if si and req.setETag('DIR:%s-%s' % (base32.b2a(si), t or "")):
163                 return ""
164
165         if not t:
166             # render the directory as HTML, using the docFactory and Nevow's
167             # whole templating thing.
168             return DirectoryAsHTML(self.node,
169                                    self.client.mutable_file_default)
170
171         if t == "json":
172             return DirectoryJSONMetadata(ctx, self.node)
173         if t == "info":
174             return MoreInfo(self.node)
175         if t == "uri":
176             return DirectoryURI(ctx, self.node)
177         if t == "readonly-uri":
178             return DirectoryReadonlyURI(ctx, self.node)
179         if t == 'rename-form':
180             return RenameForm(self.node)
181
182         raise WebError("GET directory: bad t=%s" % t)
183
184     def render_PUT(self, ctx):
185         req = IRequest(ctx)
186         t = get_arg(req, "t", "").strip()
187         replace = parse_replace_arg(get_arg(req, "replace", "true"))
188
189         if t == "mkdir":
190             # our job was done by the traversal/create-intermediate-directory
191             # process that got us here.
192             return text_plain(self.node.get_uri(), ctx) # TODO: urlencode
193         if t == "uri":
194             if not replace:
195                 # they're trying to set_uri and that name is already occupied
196                 # (by us).
197                 raise ExistingChildError()
198             d = self.replace_me_with_a_childcap(req, self.client, replace)
199             # TODO: results
200             return d
201
202         raise WebError("PUT to a directory")
203
204     def render_POST(self, ctx):
205         req = IRequest(ctx)
206         t = get_arg(req, "t", "").strip()
207
208         if t == "mkdir":
209             d = self._POST_mkdir(req)
210         elif t == "mkdir-with-children":
211             d = self._POST_mkdir_with_children(req)
212         elif t == "mkdir-immutable":
213             d = self._POST_mkdir_immutable(req)
214         elif t == "upload":
215             d = self._POST_upload(ctx) # this one needs the context
216         elif t == "uri":
217             d = self._POST_uri(req)
218         elif t == "delete" or t == "unlink":
219             d = self._POST_unlink(req)
220         elif t == "rename":
221             d = self._POST_rename(req)
222         elif t == "move":
223             d = self._POST_move(req)
224         elif t == "check":
225             d = self._POST_check(req)
226         elif t == "start-deep-check":
227             d = self._POST_start_deep_check(ctx)
228         elif t == "stream-deep-check":
229             d = self._POST_stream_deep_check(ctx)
230         elif t == "start-manifest":
231             d = self._POST_start_manifest(ctx)
232         elif t == "start-deep-size":
233             d = self._POST_start_deep_size(ctx)
234         elif t == "start-deep-stats":
235             d = self._POST_start_deep_stats(ctx)
236         elif t == "stream-manifest":
237             d = self._POST_stream_manifest(ctx)
238         elif t == "set_children" or t == "set-children":
239             d = self._POST_set_children(req)
240         else:
241             raise WebError("POST to a directory with bad t=%s" % t)
242
243         when_done = get_arg(req, "when_done", None)
244         if when_done:
245             d.addCallback(lambda res: url.URL.fromString(when_done))
246         return d
247
248     def _POST_mkdir(self, req):
249         name = get_arg(req, "name", "")
250         if not name:
251             # our job is done, it was handled by the code in got_child
252             # which created the final directory (i.e. us)
253             return defer.succeed(self.node.get_uri()) # TODO: urlencode
254         name = name.decode("utf-8")
255         replace = boolean_of_arg(get_arg(req, "replace", "true"))
256         kids = {}
257         mt = get_mutable_type(get_format(req, None))
258         d = self.node.create_subdirectory(name, kids, overwrite=replace,
259                                           mutable_version=mt)
260         d.addCallback(lambda child: child.get_uri()) # TODO: urlencode
261         return d
262
263     def _POST_mkdir_with_children(self, req):
264         name = get_arg(req, "name", "")
265         if not name:
266             # our job is done, it was handled by the code in got_child
267             # which created the final directory (i.e. us)
268             return defer.succeed(self.node.get_uri()) # TODO: urlencode
269         name = name.decode("utf-8")
270         # TODO: decide on replace= behavior, see #903
271         #replace = boolean_of_arg(get_arg(req, "replace", "false"))
272         req.content.seek(0)
273         kids_json = req.content.read()
274         kids = convert_children_json(self.client.nodemaker, kids_json)
275         mt = get_mutable_type(get_format(req, None))
276         d = self.node.create_subdirectory(name, kids, overwrite=False,
277                                           mutable_version=mt)
278         d.addCallback(lambda child: child.get_uri()) # TODO: urlencode
279         return d
280
281     def _POST_mkdir_immutable(self, req):
282         name = get_arg(req, "name", "")
283         if not name:
284             # our job is done, it was handled by the code in got_child
285             # which created the final directory (i.e. us)
286             return defer.succeed(self.node.get_uri()) # TODO: urlencode
287         name = name.decode("utf-8")
288         # TODO: decide on replace= behavior, see #903
289         #replace = boolean_of_arg(get_arg(req, "replace", "false"))
290         req.content.seek(0)
291         kids_json = req.content.read()
292         kids = convert_children_json(self.client.nodemaker, kids_json)
293         d = self.node.create_subdirectory(name, kids, overwrite=False, mutable=False)
294         d.addCallback(lambda child: child.get_uri()) # TODO: urlencode
295         return d
296
297     def _POST_upload(self, ctx):
298         req = IRequest(ctx)
299         charset = get_arg(req, "_charset", "utf-8")
300         contents = req.fields["file"]
301         assert contents.filename is None or isinstance(contents.filename, str)
302         name = get_arg(req, "name")
303         name = name or contents.filename
304         if name is not None:
305             name = name.strip()
306         if not name:
307             # this prohibts empty, missing, and all-whitespace filenames
308             raise WebError("upload requires a name")
309         assert isinstance(name, str)
310         name = name.decode(charset)
311         if "/" in name:
312             raise WebError("name= may not contain a slash", http.BAD_REQUEST)
313         assert isinstance(name, unicode)
314
315         # since POST /uri/path/file?t=upload is equivalent to
316         # POST /uri/path/dir?t=upload&name=foo, just do the same thing that
317         # childFactory would do. Things are cleaner if we only do a subset of
318         # them, though, so we don't do: d = self.childFactory(ctx, name)
319
320         d = self.node.get(name)
321         def _maybe_got_node(node_or_failure):
322             if isinstance(node_or_failure, Failure):
323                 f = node_or_failure
324                 f.trap(NoSuchChildError)
325                 # create a placeholder which will see POST t=upload
326                 return PlaceHolderNodeHandler(self.client, self.node, name)
327             else:
328                 node = node_or_failure
329                 return make_handler_for(node, self.client, self.node, name)
330         d.addBoth(_maybe_got_node)
331         # now we have a placeholder or a filenodehandler, and we can just
332         # delegate to it. We could return the resource back out of
333         # DirectoryNodeHandler.renderHTTP, and nevow would recurse into it,
334         # but the addCallback() that handles when_done= would break.
335         d.addCallback(lambda child: child.renderHTTP(ctx))
336         return d
337
338     def _POST_uri(self, req):
339         childcap = get_arg(req, "uri")
340         if not childcap:
341             raise WebError("set-uri requires a uri")
342         name = get_arg(req, "name")
343         if not name:
344             raise WebError("set-uri requires a name")
345         charset = get_arg(req, "_charset", "utf-8")
346         name = name.decode(charset)
347         replace = boolean_of_arg(get_arg(req, "replace", "true"))
348
349         # We mustn't pass childcap for the readcap argument because we don't
350         # know whether it is a read cap. Passing a read cap as the writecap
351         # argument will work (it ends up calling NodeMaker.create_from_cap,
352         # which derives a readcap if necessary and possible).
353         d = self.node.set_uri(name, childcap, None, overwrite=replace)
354         d.addCallback(lambda res: childcap)
355         return d
356
357     def _POST_unlink(self, req):
358         name = get_arg(req, "name")
359         if name is None:
360             # apparently an <input type="hidden" name="name" value="">
361             # won't show up in the resulting encoded form.. the 'name'
362             # field is completely missing. So to allow unlinking of a
363             # child with a name that is the empty string, we have to
364             # pretend that None means ''. The only downside of this is
365             # a slightly confusing error message if someone does a POST
366             # without a name= field. For our own HTML this isn't a big
367             # deal, because we create the 'unlink' POST buttons ourselves.
368             name = ''
369         charset = get_arg(req, "_charset", "utf-8")
370         name = name.decode(charset)
371         d = self.node.delete(name)
372         d.addCallback(lambda res: "thing unlinked")
373         return d
374
375     def _POST_rename(self, req):
376         charset = get_arg(req, "_charset", "utf-8")
377         from_name = get_arg(req, "from_name")
378         if from_name is not None:
379             from_name = from_name.strip()
380             from_name = from_name.decode(charset)
381             assert isinstance(from_name, unicode)
382         to_name = get_arg(req, "to_name")
383         if to_name is not None:
384             to_name = to_name.strip()
385             to_name = to_name.decode(charset)
386             assert isinstance(to_name, unicode)
387         if not from_name or not to_name:
388             raise WebError("rename requires from_name and to_name")
389         if from_name == to_name:
390             return defer.succeed("redundant rename")
391
392         # allow from_name to contain slashes, so they can fix names that were
393         # accidentally created with them. But disallow them in to_name, to
394         # discourage the practice.
395         if "/" in to_name:
396             raise WebError("to_name= may not contain a slash", http.BAD_REQUEST)
397
398         replace = boolean_of_arg(get_arg(req, "replace", "true"))
399         d = self.node.move_child_to(from_name, self.node, to_name, replace)
400         d.addCallback(lambda res: "thing renamed")
401         return d
402
403     def _POST_move(self, req):
404         charset = get_arg(req, "_charset", "utf-8")
405         from_name = get_arg(req, "from_name")
406         if from_name is not None:
407             from_name = from_name.strip()
408             from_name = from_name.decode(charset)
409             assert isinstance(from_name, unicode)
410         to_name = get_arg(req, "to_name")
411         if to_name is not None:
412             to_name = to_name.strip()
413             to_name = to_name.decode(charset)
414             assert isinstance(to_name, unicode)
415         if not to_name:
416             to_name = from_name
417         to_dir = get_arg(req, "to_dir")
418         if to_dir is not None:
419             to_dir = to_dir.strip()
420             to_dir = to_dir.decode(charset)
421             assert isinstance(to_dir, unicode)
422         if not from_name or not to_dir:
423             raise WebError("move requires from_name and to_dir")
424         replace = boolean_of_arg(get_arg(req, "replace", "true"))
425
426         # Disallow slashes in both from_name and to_name, that would only
427         # cause confusion. t=move is only for moving things from the
428         # *current* directory into a second directory named by to_dir=
429         if "/" in from_name:
430             raise WebError("from_name= may not contain a slash",
431                            http.BAD_REQUEST)
432         if "/" in to_name:
433             raise WebError("to_name= may not contain a slash",
434                            http.BAD_REQUEST)
435
436         target_type = get_arg(req, "target_type", "name")
437         if target_type == "name":
438             d = self.node.get_child_at_path(to_dir)
439         elif target_type == "uri":
440             d = defer.succeed(self.client.create_node_from_uri(str(to_dir)))
441         else:
442             raise WebError("invalid target_type parameter", http.BAD_REQUEST)
443
444         def is_target_node_usable(target_node):
445             if not IDirectoryNode.providedBy(target_node):
446                 raise WebError("to_dir is not a directory", http.BAD_REQUEST)
447             return target_node
448         d.addCallback(is_target_node_usable)
449         d.addCallback(lambda new_parent:
450                       self.node.move_child_to(from_name, new_parent,
451                                               to_name, replace))
452         d.addCallback(lambda res: "thing moved")
453         return d
454
455     def _maybe_literal(self, res, Results_Class):
456         if res:
457             return Results_Class(self.client, res)
458         return LiteralCheckResultsRenderer(self.client)
459
460     def _POST_check(self, req):
461         # check this directory
462         verify = boolean_of_arg(get_arg(req, "verify", "false"))
463         repair = boolean_of_arg(get_arg(req, "repair", "false"))
464         add_lease = boolean_of_arg(get_arg(req, "add-lease", "false"))
465         if repair:
466             d = self.node.check_and_repair(Monitor(), verify, add_lease)
467             d.addCallback(self._maybe_literal, CheckAndRepairResultsRenderer)
468         else:
469             d = self.node.check(Monitor(), verify, add_lease)
470             d.addCallback(self._maybe_literal, CheckResultsRenderer)
471         return d
472
473     def _start_operation(self, monitor, renderer, ctx):
474         table = IOpHandleTable(ctx)
475         table.add_monitor(ctx, monitor, renderer)
476         return table.redirect_to(ctx)
477
478     def _POST_start_deep_check(self, ctx):
479         # check this directory and everything reachable from it
480         if not get_arg(ctx, "ophandle"):
481             raise NeedOperationHandleError("slow operation requires ophandle=")
482         verify = boolean_of_arg(get_arg(ctx, "verify", "false"))
483         repair = boolean_of_arg(get_arg(ctx, "repair", "false"))
484         add_lease = boolean_of_arg(get_arg(ctx, "add-lease", "false"))
485         if repair:
486             monitor = self.node.start_deep_check_and_repair(verify, add_lease)
487             renderer = DeepCheckAndRepairResultsRenderer(self.client, monitor)
488         else:
489             monitor = self.node.start_deep_check(verify, add_lease)
490             renderer = DeepCheckResultsRenderer(self.client, monitor)
491         return self._start_operation(monitor, renderer, ctx)
492
493     def _POST_stream_deep_check(self, ctx):
494         verify = boolean_of_arg(get_arg(ctx, "verify", "false"))
495         repair = boolean_of_arg(get_arg(ctx, "repair", "false"))
496         add_lease = boolean_of_arg(get_arg(ctx, "add-lease", "false"))
497         walker = DeepCheckStreamer(ctx, self.node, verify, repair, add_lease)
498         monitor = self.node.deep_traverse(walker)
499         walker.setMonitor(monitor)
500         # register to hear stopProducing. The walker ignores pauseProducing.
501         IRequest(ctx).registerProducer(walker, True)
502         d = monitor.when_done()
503         def _done(res):
504             IRequest(ctx).unregisterProducer()
505             return res
506         d.addBoth(_done)
507         def _cancelled(f):
508             f.trap(OperationCancelledError)
509             return "Operation Cancelled"
510         d.addErrback(_cancelled)
511         def _error(f):
512             # signal the error as a non-JSON "ERROR:" line, plus exception
513             msg = "ERROR: %s(%s)\n" % (f.value.__class__.__name__,
514                                        ", ".join([str(a) for a in f.value.args]))
515             msg += str(f)
516             return msg
517         d.addErrback(_error)
518         return d
519
520     def _POST_start_manifest(self, ctx):
521         if not get_arg(ctx, "ophandle"):
522             raise NeedOperationHandleError("slow operation requires ophandle=")
523         monitor = self.node.build_manifest()
524         renderer = ManifestResults(self.client, monitor)
525         return self._start_operation(monitor, renderer, ctx)
526
527     def _POST_start_deep_size(self, ctx):
528         if not get_arg(ctx, "ophandle"):
529             raise NeedOperationHandleError("slow operation requires ophandle=")
530         monitor = self.node.start_deep_stats()
531         renderer = DeepSizeResults(self.client, monitor)
532         return self._start_operation(monitor, renderer, ctx)
533
534     def _POST_start_deep_stats(self, ctx):
535         if not get_arg(ctx, "ophandle"):
536             raise NeedOperationHandleError("slow operation requires ophandle=")
537         monitor = self.node.start_deep_stats()
538         renderer = DeepStatsResults(self.client, monitor)
539         return self._start_operation(monitor, renderer, ctx)
540
541     def _POST_stream_manifest(self, ctx):
542         walker = ManifestStreamer(ctx, self.node)
543         monitor = self.node.deep_traverse(walker)
544         walker.setMonitor(monitor)
545         # register to hear stopProducing. The walker ignores pauseProducing.
546         IRequest(ctx).registerProducer(walker, True)
547         d = monitor.when_done()
548         def _done(res):
549             IRequest(ctx).unregisterProducer()
550             return res
551         d.addBoth(_done)
552         def _cancelled(f):
553             f.trap(OperationCancelledError)
554             return "Operation Cancelled"
555         d.addErrback(_cancelled)
556         def _error(f):
557             # signal the error as a non-JSON "ERROR:" line, plus exception
558             msg = "ERROR: %s(%s)\n" % (f.value.__class__.__name__,
559                                        ", ".join([str(a) for a in f.value.args]))
560             msg += str(f)
561             return msg
562         d.addErrback(_error)
563         return d
564
565     def _POST_set_children(self, req):
566         replace = boolean_of_arg(get_arg(req, "replace", "true"))
567         req.content.seek(0)
568         body = req.content.read()
569         try:
570             children = simplejson.loads(body)
571         except ValueError, le:
572             le.args = tuple(le.args + (body,))
573             # TODO test handling of bad JSON
574             raise
575         cs = {}
576         for name, (file_or_dir, mddict) in children.iteritems():
577             name = unicode(name) # simplejson-2.0.1 returns str *or* unicode
578             writecap = mddict.get('rw_uri')
579             if writecap is not None:
580                 writecap = str(writecap)
581             readcap = mddict.get('ro_uri')
582             if readcap is not None:
583                 readcap = str(readcap)
584             cs[name] = (writecap, readcap, mddict.get('metadata'))
585         d = self.node.set_children(cs, replace)
586         d.addCallback(lambda res: "Okay so I did it.")
587         # TODO: results
588         return d
589
590 def abbreviated_dirnode(dirnode):
591     u = from_string_dirnode(dirnode.get_uri())
592     return u.abbrev_si()
593
594 SPACE = u"\u00A0"*2
595
596 class DirectoryAsHTML(rend.Page):
597     # The remainder of this class is to render the directory into
598     # human+browser -oriented HTML.
599     docFactory = getxmlfile("directory.xhtml")
600     addSlash = True
601
602     def __init__(self, node, default_mutable_format):
603         rend.Page.__init__(self)
604         self.node = node
605
606         assert default_mutable_format in (MDMF_VERSION, SDMF_VERSION)
607         self.default_mutable_format = default_mutable_format
608
609     def beforeRender(self, ctx):
610         # attempt to get the dirnode's children, stashing them (or the
611         # failure that results) for later use
612         d = self.node.list()
613         def _good(children):
614             # Deferreds don't optimize out tail recursion, and the way
615             # Nevow's flattener handles Deferreds doesn't take this into
616             # account. As a result, large lists of Deferreds that fire in the
617             # same turn (i.e. the output of defer.succeed) will cause a stack
618             # overflow. To work around this, we insert a turn break after
619             # every 100 items, using foolscap's fireEventually(). This gives
620             # the stack a chance to be popped. It would also work to put
621             # every item in its own turn, but that'd be a lot more
622             # inefficient. This addresses ticket #237, for which I was never
623             # able to create a failing unit test.
624             output = []
625             for i,item in enumerate(sorted(children.items())):
626                 if i % 100 == 0:
627                     output.append(fireEventually(item))
628                 else:
629                     output.append(item)
630             self.dirnode_children = output
631             return ctx
632         def _bad(f):
633             text, code = humanize_failure(f)
634             self.dirnode_children = None
635             self.dirnode_children_error = text
636             return ctx
637         d.addCallbacks(_good, _bad)
638         return d
639
640     def render_title(self, ctx, data):
641         si_s = abbreviated_dirnode(self.node)
642         header = ["Tahoe-LAFS - Directory SI=%s" % si_s]
643         if self.node.is_unknown():
644             header.append(" (unknown)")
645         elif not self.node.is_mutable():
646             header.append(" (immutable)")
647         elif self.node.is_readonly():
648             header.append(" (read-only)")
649         else:
650             header.append(" (modifiable)")
651         return ctx.tag[header]
652
653     def render_header(self, ctx, data):
654         si_s = abbreviated_dirnode(self.node)
655         header = ["Tahoe-LAFS Directory SI=", T.span(class_="data-chars")[si_s]]
656         if self.node.is_unknown():
657             header.append(" (unknown)")
658         elif not self.node.is_mutable():
659             header.append(" (immutable)")
660         elif self.node.is_readonly():
661             header.append(" (read-only)")
662         return ctx.tag[header]
663
664     def render_welcome(self, ctx, data):
665         link = get_root(ctx)
666         return ctx.tag[T.a(href=link)["Return to Welcome page"]]
667
668     def render_show_readonly(self, ctx, data):
669         if self.node.is_unknown() or self.node.is_readonly():
670             return ""
671         rocap = self.node.get_readonly_uri()
672         root = get_root(ctx)
673         uri_link = "%s/uri/%s/" % (root, urllib.quote(rocap))
674         return ctx.tag[T.a(href=uri_link)["Read-Only Version"]]
675
676     def render_try_children(self, ctx, data):
677         # if the dirnode can be retrived, render a table of children.
678         # Otherwise, render an apologetic error message.
679         if self.dirnode_children is not None:
680             return ctx.tag
681         else:
682             return T.div[T.p["Error reading directory:"],
683                          T.p[self.dirnode_children_error]]
684
685     def data_children(self, ctx, data):
686         return self.dirnode_children
687
688     def render_row(self, ctx, data):
689         name, (target, metadata) = data
690         name = name.encode("utf-8")
691         assert not isinstance(name, unicode)
692         nameurl = urllib.quote(name, safe="") # encode any slashes too
693
694         root = get_root(ctx)
695         here = "%s/uri/%s/" % (root, urllib.quote(self.node.get_uri()))
696         if self.node.is_unknown() or self.node.is_readonly():
697             unlink = "-"
698             rename = "-"
699         else:
700             # this creates a button which will cause our _POST_unlink method
701             # to be invoked, which unlinks the file and then redirects the
702             # browser back to this directory
703             unlink = T.form(action=here, method="post")[
704                 T.input(type='hidden', name='t', value='unlink'),
705                 T.input(type='hidden', name='name', value=name),
706                 T.input(type='hidden', name='when_done', value="."),
707                 T.input(type='submit', value='unlink', name="unlink"),
708                 ]
709
710             rename = T.form(action=here, method="get")[
711                 T.input(type='hidden', name='t', value='rename-form'),
712                 T.input(type='hidden', name='name', value=name),
713                 T.input(type='hidden', name='when_done', value="."),
714                 T.input(type='submit', value='rename/move', name="rename"),
715                 ]
716
717         ctx.fillSlots("unlink", unlink)
718         ctx.fillSlots("rename", rename)
719
720         times = []
721         linkcrtime = metadata.get('tahoe', {}).get("linkcrtime")
722         if linkcrtime is not None:
723             times.append("lcr: " + time_format.iso_local(linkcrtime))
724         else:
725             # For backwards-compatibility with links last modified by Tahoe < 1.4.0:
726             if "ctime" in metadata:
727                 ctime = time_format.iso_local(metadata["ctime"])
728                 times.append("c: " + ctime)
729         linkmotime = metadata.get('tahoe', {}).get("linkmotime")
730         if linkmotime is not None:
731             if times:
732                 times.append(T.br())
733             times.append("lmo: " + time_format.iso_local(linkmotime))
734         else:
735             # For backwards-compatibility with links last modified by Tahoe < 1.4.0:
736             if "mtime" in metadata:
737                 mtime = time_format.iso_local(metadata["mtime"])
738                 if times:
739                     times.append(T.br())
740                 times.append("m: " + mtime)
741         ctx.fillSlots("times", times)
742
743         assert IFilesystemNode.providedBy(target), target
744         target_uri = target.get_uri() or ""
745         quoted_uri = urllib.quote(target_uri, safe="") # escape slashes too
746
747         if IMutableFileNode.providedBy(target):
748             # to prevent javascript in displayed .html files from stealing a
749             # secret directory URI from the URL, send the browser to a URI-based
750             # page that doesn't know about the directory at all
751             dlurl = "%s/file/%s/@@named=/%s" % (root, quoted_uri, nameurl)
752
753             ctx.fillSlots("filename", T.a(href=dlurl)[name])
754             ctx.fillSlots("type", "SSK")
755
756             ctx.fillSlots("size", "?")
757
758             info_link = "%s/uri/%s?t=info" % (root, quoted_uri)
759
760         elif IImmutableFileNode.providedBy(target):
761             dlurl = "%s/file/%s/@@named=/%s" % (root, quoted_uri, nameurl)
762
763             ctx.fillSlots("filename", T.a(href=dlurl)[name])
764             ctx.fillSlots("type", "FILE")
765
766             ctx.fillSlots("size", target.get_size())
767
768             info_link = "%s/uri/%s?t=info" % (root, quoted_uri)
769
770         elif IDirectoryNode.providedBy(target):
771             # directory
772             uri_link = "%s/uri/%s/" % (root, urllib.quote(target_uri))
773             ctx.fillSlots("filename", T.a(href=uri_link)[name])
774             if not target.is_mutable():
775                 dirtype = "DIR-IMM"
776             elif target.is_readonly():
777                 dirtype = "DIR-RO"
778             else:
779                 dirtype = "DIR"
780             ctx.fillSlots("type", dirtype)
781             ctx.fillSlots("size", "-")
782             info_link = "%s/uri/%s/?t=info" % (root, quoted_uri)
783
784         elif isinstance(target, ProhibitedNode):
785             ctx.fillSlots("filename", T.strike[name])
786             if IDirectoryNode.providedBy(target.wrapped_node):
787                 blacklisted_type = "DIR-BLACKLISTED"
788             else:
789                 blacklisted_type = "BLACKLISTED"
790             ctx.fillSlots("type", blacklisted_type)
791             ctx.fillSlots("size", "-")
792             info_link = None
793             ctx.fillSlots("info", ["Access Prohibited:", T.br, target.reason])
794
795         else:
796             # unknown
797             ctx.fillSlots("filename", name)
798             if target.get_write_uri() is not None:
799                 unknowntype = "?"
800             elif not self.node.is_mutable() or target.is_alleged_immutable():
801                 unknowntype = "?-IMM"
802             else:
803                 unknowntype = "?-RO"
804             ctx.fillSlots("type", unknowntype)
805             ctx.fillSlots("size", "-")
806             # use a directory-relative info link, so we can extract both the
807             # writecap and the readcap
808             info_link = "%s?t=info" % urllib.quote(name)
809
810         if info_link:
811             ctx.fillSlots("info", T.a(href=info_link)["More Info"])
812
813         return ctx.tag
814
815     # XXX: similar to render_upload_form and render_mkdir_form in root.py.
816     def render_forms(self, ctx, data):
817         forms = []
818
819         if self.node.is_readonly():
820             return T.div["No upload forms: directory is read-only"]
821         if self.dirnode_children is None:
822             return T.div["No upload forms: directory is unreadable"]
823
824         mkdir_sdmf = T.input(type='radio', name='format',
825                              value='sdmf', id='mkdir-sdmf',
826                              checked='checked')
827         mkdir_mdmf = T.input(type='radio', name='format',
828                              value='mdmf', id='mkdir-mdmf')
829
830         mkdir_form = T.form(action=".", method="post",
831                             enctype="multipart/form-data")[
832             T.fieldset[
833             T.input(type="hidden", name="t", value="mkdir"),
834             T.input(type="hidden", name="when_done", value="."),
835             T.legend(class_="freeform-form-label")["Create a new directory in this directory"],
836             "New directory name:"+SPACE,
837             T.input(type="text", name="name"), SPACE,
838             T.input(type="submit", value="Create"), SPACE*2,
839             mkdir_sdmf, T.label(for_='mutable-directory-sdmf')[" SDMF"], SPACE,
840             mkdir_mdmf, T.label(for_='mutable-directory-mdmf')[" MDMF (experimental)"],
841             ]]
842         forms.append(T.div(class_="freeform-form")[mkdir_form])
843
844         upload_chk  = T.input(type='radio', name='format',
845                               value='chk', id='upload-chk',
846                               checked='checked')
847         upload_sdmf = T.input(type='radio', name='format',
848                               value='sdmf', id='upload-sdmf')
849         upload_mdmf = T.input(type='radio', name='format',
850                               value='mdmf', id='upload-mdmf')
851
852         upload_form = T.form(action=".", method="post",
853                              enctype="multipart/form-data")[
854             T.fieldset[
855             T.input(type="hidden", name="t", value="upload"),
856             T.input(type="hidden", name="when_done", value="."),
857             T.legend(class_="freeform-form-label")["Upload a file to this directory"],
858             "Choose a file to upload:"+SPACE,
859             T.input(type="file", name="file", class_="freeform-input-file"), SPACE,
860             T.input(type="submit", value="Upload"),                          SPACE*2,
861             upload_chk,  T.label(for_="upload-chk") [" Immutable"],          SPACE,
862             upload_sdmf, T.label(for_="upload-sdmf")[" SDMF"],               SPACE,
863             upload_mdmf, T.label(for_="upload-mdmf")[" MDMF (experimental)"],
864             ]]
865         forms.append(T.div(class_="freeform-form")[upload_form])
866
867         attach_form = T.form(action=".", method="post",
868                              enctype="multipart/form-data")[
869             T.fieldset[
870             T.input(type="hidden", name="t", value="uri"),
871             T.input(type="hidden", name="when_done", value="."),
872             T.legend(class_="freeform-form-label")["Add a link to a file or directory which is already in Tahoe-LAFS."],
873             "New child name:"+SPACE,
874             T.input(type="text", name="name"), SPACE*2,
875             "URI of new child:"+SPACE,
876             T.input(type="text", name="uri"), SPACE,
877             T.input(type="submit", value="Attach"),
878             ]]
879         forms.append(T.div(class_="freeform-form")[attach_form])
880         return forms
881
882     def render_results(self, ctx, data):
883         req = IRequest(ctx)
884         return get_arg(req, "results", "")
885
886
887 def DirectoryJSONMetadata(ctx, dirnode):
888     d = dirnode.list()
889     def _got(children):
890         kids = {}
891         for name, (childnode, metadata) in children.iteritems():
892             assert IFilesystemNode.providedBy(childnode), childnode
893             rw_uri = childnode.get_write_uri()
894             ro_uri = childnode.get_readonly_uri()
895             if IFileNode.providedBy(childnode):
896                 kiddata = ("filenode", {'size': childnode.get_size(),
897                                         'mutable': childnode.is_mutable(),
898                                         })
899                 if childnode.is_mutable():
900                     mutable_type = childnode.get_version()
901                     assert mutable_type in (SDMF_VERSION, MDMF_VERSION)
902                     if mutable_type == MDMF_VERSION:
903                         file_format = "MDMF"
904                     else:
905                         file_format = "SDMF"
906                 else:
907                     file_format = "CHK"
908                 kiddata[1]['format'] = file_format
909
910             elif IDirectoryNode.providedBy(childnode):
911                 kiddata = ("dirnode", {'mutable': childnode.is_mutable()})
912             else:
913                 kiddata = ("unknown", {})
914
915             kiddata[1]["metadata"] = metadata
916             if rw_uri:
917                 kiddata[1]["rw_uri"] = rw_uri
918             if ro_uri:
919                 kiddata[1]["ro_uri"] = ro_uri
920             verifycap = childnode.get_verify_cap()
921             if verifycap:
922                 kiddata[1]['verify_uri'] = verifycap.to_string()
923
924             kids[name] = kiddata
925
926         drw_uri = dirnode.get_write_uri()
927         dro_uri = dirnode.get_readonly_uri()
928         contents = { 'children': kids }
929         if dro_uri:
930             contents['ro_uri'] = dro_uri
931         if drw_uri:
932             contents['rw_uri'] = drw_uri
933         verifycap = dirnode.get_verify_cap()
934         if verifycap:
935             contents['verify_uri'] = verifycap.to_string()
936         contents['mutable'] = dirnode.is_mutable()
937         data = ("dirnode", contents)
938         json = simplejson.dumps(data, indent=1) + "\n"
939         return json
940     d.addCallback(_got)
941     d.addCallback(text_plain, ctx)
942     return d
943
944
945 def DirectoryURI(ctx, dirnode):
946     return text_plain(dirnode.get_uri(), ctx)
947
948 def DirectoryReadonlyURI(ctx, dirnode):
949     return text_plain(dirnode.get_readonly_uri(), ctx)
950
951 class RenameForm(rend.Page):
952     addSlash = True
953     docFactory = getxmlfile("rename-form.xhtml")
954
955     def render_title(self, ctx, data):
956         return ctx.tag["Directory SI=%s" % abbreviated_dirnode(self.original)]
957
958     def render_header(self, ctx, data):
959         header = ["Rename "
960                   "in directory SI=%s" % abbreviated_dirnode(self.original),
961                   ]
962
963         if self.original.is_readonly():
964             header.append(" (readonly!)")
965         header.append(":")
966         return ctx.tag[header]
967
968     def render_when_done(self, ctx, data):
969         return T.input(type="hidden", name="when_done", value=".")
970
971     def render_get_name(self, ctx, data):
972         req = IRequest(ctx)
973         name = get_arg(req, "name", "")
974         ctx.tag.attributes['value'] = name
975         return ctx.tag
976
977 class ManifestResults(rend.Page, ReloadMixin):
978     docFactory = getxmlfile("manifest.xhtml")
979
980     def __init__(self, client, monitor):
981         self.client = client
982         self.monitor = monitor
983
984     def renderHTTP(self, ctx):
985         req = inevow.IRequest(ctx)
986         output = get_arg(req, "output", "html").lower()
987         if output == "text":
988             return self.text(req)
989         if output == "json":
990             return self.json(req)
991         return rend.Page.renderHTTP(self, ctx)
992
993     def slashify_path(self, path):
994         if not path:
995             return ""
996         return "/".join([p.encode("utf-8") for p in path])
997
998     def text(self, req):
999         req.setHeader("content-type", "text/plain")
1000         lines = []
1001         is_finished = self.monitor.is_finished()
1002         lines.append("finished: " + {True: "yes", False: "no"}[is_finished])
1003         for (path, cap) in self.monitor.get_status()["manifest"]:
1004             lines.append(self.slashify_path(path) + " " + cap)
1005         return "\n".join(lines) + "\n"
1006
1007     def json(self, req):
1008         req.setHeader("content-type", "text/plain")
1009         m = self.monitor
1010         s = m.get_status()
1011
1012         if m.origin_si:
1013             origin_base32 = base32.b2a(m.origin_si)
1014         else:
1015             origin_base32 = ""
1016         status = { "stats": s["stats"],
1017                    "finished": m.is_finished(),
1018                    "origin": origin_base32,
1019                    }
1020         if m.is_finished():
1021             # don't return manifest/verifycaps/SIs unless the operation is
1022             # done, to save on CPU/memory (both here and in the HTTP client
1023             # who has to unpack the JSON). Tests show that the ManifestWalker
1024             # needs about 1092 bytes per item, the JSON we generate here
1025             # requires about 503 bytes per item, and some internal overhead
1026             # (perhaps transport-layer buffers in twisted.web?) requires an
1027             # additional 1047 bytes per item.
1028             status.update({ "manifest": s["manifest"],
1029                             "verifycaps": [i for i in s["verifycaps"]],
1030                             "storage-index": [i for i in s["storage-index"]],
1031                             })
1032             # simplejson doesn't know how to serialize a set. We use a
1033             # generator that walks the set rather than list(setofthing) to
1034             # save a small amount of memory (4B*len) and a moderate amount of
1035             # CPU.
1036         return simplejson.dumps(status, indent=1)
1037
1038     def _si_abbrev(self):
1039         si = self.monitor.origin_si
1040         if not si:
1041             return "<LIT>"
1042         return base32.b2a(si)[:6]
1043
1044     def render_title(self, ctx):
1045         return T.title["Manifest of SI=%s" % self._si_abbrev()]
1046
1047     def render_header(self, ctx):
1048         return T.p["Manifest of SI=%s" % self._si_abbrev()]
1049
1050     def data_items(self, ctx, data):
1051         return self.monitor.get_status()["manifest"]
1052
1053     def render_row(self, ctx, (path, cap)):
1054         ctx.fillSlots("path", self.slashify_path(path))
1055         root = get_root(ctx)
1056         # TODO: we need a clean consistent way to get the type of a cap string
1057         if cap:
1058             if cap.startswith("URI:CHK") or cap.startswith("URI:SSK"):
1059                 nameurl = urllib.quote(path[-1].encode("utf-8"))
1060                 uri_link = "%s/file/%s/@@named=/%s" % (root, urllib.quote(cap),
1061                                                        nameurl)
1062             else:
1063                 uri_link = "%s/uri/%s" % (root, urllib.quote(cap, safe=""))
1064             ctx.fillSlots("cap", T.a(href=uri_link)[cap])
1065         else:
1066             ctx.fillSlots("cap", "")
1067         return ctx.tag
1068
1069 class DeepSizeResults(rend.Page):
1070     def __init__(self, client, monitor):
1071         self.client = client
1072         self.monitor = monitor
1073
1074     def renderHTTP(self, ctx):
1075         req = inevow.IRequest(ctx)
1076         output = get_arg(req, "output", "html").lower()
1077         req.setHeader("content-type", "text/plain")
1078         if output == "json":
1079             return self.json(req)
1080         # plain text
1081         is_finished = self.monitor.is_finished()
1082         output = "finished: " + {True: "yes", False: "no"}[is_finished] + "\n"
1083         if is_finished:
1084             stats = self.monitor.get_status()
1085             total = (stats.get("size-immutable-files", 0)
1086                      + stats.get("size-mutable-files", 0)
1087                      + stats.get("size-directories", 0))
1088             output += "size: %d\n" % total
1089         return output
1090
1091     def json(self, req):
1092         status = {"finished": self.monitor.is_finished(),
1093                   "size": self.monitor.get_status(),
1094                   }
1095         return simplejson.dumps(status)
1096
1097 class DeepStatsResults(rend.Page):
1098     def __init__(self, client, monitor):
1099         self.client = client
1100         self.monitor = monitor
1101
1102     def renderHTTP(self, ctx):
1103         # JSON only
1104         inevow.IRequest(ctx).setHeader("content-type", "text/plain")
1105         s = self.monitor.get_status().copy()
1106         s["finished"] = self.monitor.is_finished()
1107         return simplejson.dumps(s, indent=1)
1108
1109 class ManifestStreamer(dirnode.DeepStats):
1110     implements(IPushProducer)
1111
1112     def __init__(self, ctx, origin):
1113         dirnode.DeepStats.__init__(self, origin)
1114         self.req = IRequest(ctx)
1115
1116     def setMonitor(self, monitor):
1117         self.monitor = monitor
1118     def pauseProducing(self):
1119         pass
1120     def resumeProducing(self):
1121         pass
1122     def stopProducing(self):
1123         self.monitor.cancel()
1124
1125     def add_node(self, node, path):
1126         dirnode.DeepStats.add_node(self, node, path)
1127         d = {"path": path,
1128              "cap": node.get_uri()}
1129
1130         if IDirectoryNode.providedBy(node):
1131             d["type"] = "directory"
1132         elif IFileNode.providedBy(node):
1133             d["type"] = "file"
1134         else:
1135             d["type"] = "unknown"
1136
1137         v = node.get_verify_cap()
1138         if v:
1139             v = v.to_string()
1140         d["verifycap"] = v or ""
1141
1142         r = node.get_repair_cap()
1143         if r:
1144             r = r.to_string()
1145         d["repaircap"] = r or ""
1146
1147         si = node.get_storage_index()
1148         if si:
1149             si = base32.b2a(si)
1150         d["storage-index"] = si or ""
1151
1152         j = simplejson.dumps(d, ensure_ascii=True)
1153         assert "\n" not in j
1154         self.req.write(j+"\n")
1155
1156     def finish(self):
1157         stats = dirnode.DeepStats.get_results(self)
1158         d = {"type": "stats",
1159              "stats": stats,
1160              }
1161         j = simplejson.dumps(d, ensure_ascii=True)
1162         assert "\n" not in j
1163         self.req.write(j+"\n")
1164         return ""
1165
1166 class DeepCheckStreamer(dirnode.DeepStats):
1167     implements(IPushProducer)
1168
1169     def __init__(self, ctx, origin, verify, repair, add_lease):
1170         dirnode.DeepStats.__init__(self, origin)
1171         self.req = IRequest(ctx)
1172         self.verify = verify
1173         self.repair = repair
1174         self.add_lease = add_lease
1175
1176     def setMonitor(self, monitor):
1177         self.monitor = monitor
1178     def pauseProducing(self):
1179         pass
1180     def resumeProducing(self):
1181         pass
1182     def stopProducing(self):
1183         self.monitor.cancel()
1184
1185     def add_node(self, node, path):
1186         dirnode.DeepStats.add_node(self, node, path)
1187         data = {"path": path,
1188                 "cap": node.get_uri()}
1189
1190         if IDirectoryNode.providedBy(node):
1191             data["type"] = "directory"
1192         elif IFileNode.providedBy(node):
1193             data["type"] = "file"
1194         else:
1195             data["type"] = "unknown"
1196
1197         v = node.get_verify_cap()
1198         if v:
1199             v = v.to_string()
1200         data["verifycap"] = v or ""
1201
1202         r = node.get_repair_cap()
1203         if r:
1204             r = r.to_string()
1205         data["repaircap"] = r or ""
1206
1207         si = node.get_storage_index()
1208         if si:
1209             si = base32.b2a(si)
1210         data["storage-index"] = si or ""
1211
1212         if self.repair:
1213             d = node.check_and_repair(self.monitor, self.verify, self.add_lease)
1214             d.addCallback(self.add_check_and_repair, data)
1215         else:
1216             d = node.check(self.monitor, self.verify, self.add_lease)
1217             d.addCallback(self.add_check, data)
1218         d.addCallback(self.write_line)
1219         return d
1220
1221     def add_check_and_repair(self, crr, data):
1222         data["check-and-repair-results"] = json_check_and_repair_results(crr)
1223         return data
1224
1225     def add_check(self, cr, data):
1226         data["check-results"] = json_check_results(cr)
1227         return data
1228
1229     def write_line(self, data):
1230         j = simplejson.dumps(data, ensure_ascii=True)
1231         assert "\n" not in j
1232         self.req.write(j+"\n")
1233
1234     def finish(self):
1235         stats = dirnode.DeepStats.get_results(self)
1236         d = {"type": "stats",
1237              "stats": stats,
1238              }
1239         j = simplejson.dumps(d, ensure_ascii=True)
1240         assert "\n" not in j
1241         self.req.write(j+"\n")
1242         return ""
1243
1244
1245 class UnknownNodeHandler(RenderMixin, rend.Page):
1246     def __init__(self, client, node, parentnode=None, name=None):
1247         rend.Page.__init__(self)
1248         assert node
1249         self.node = node
1250         self.parentnode = parentnode
1251         self.name = name
1252
1253     def render_GET(self, ctx):
1254         req = IRequest(ctx)
1255         t = get_arg(req, "t", "").strip()
1256         if t == "info":
1257             return MoreInfo(self.node)
1258         if t == "json":
1259             is_parent_known_immutable = self.parentnode and not self.parentnode.is_mutable()
1260             if self.parentnode and self.name:
1261                 d = self.parentnode.get_metadata_for(self.name)
1262             else:
1263                 d = defer.succeed(None)
1264             d.addCallback(lambda md: UnknownJSONMetadata(ctx, self.node, md, is_parent_known_immutable))
1265             return d
1266         raise WebError("GET unknown URI type: can only do t=info and t=json, not t=%s.\n"
1267                        "Using a webapi server that supports a later version of Tahoe "
1268                        "may help." % t)
1269
1270 def UnknownJSONMetadata(ctx, node, edge_metadata, is_parent_known_immutable):
1271     rw_uri = node.get_write_uri()
1272     ro_uri = node.get_readonly_uri()
1273     data = ("unknown", {})
1274     if ro_uri:
1275         data[1]['ro_uri'] = ro_uri
1276     if rw_uri:
1277         data[1]['rw_uri'] = rw_uri
1278         data[1]['mutable'] = True
1279     elif is_parent_known_immutable or node.is_alleged_immutable():
1280         data[1]['mutable'] = False
1281     # else we don't know whether it is mutable.
1282
1283     if edge_metadata is not None:
1284         data[1]['metadata'] = edge_metadata
1285     return text_plain(simplejson.dumps(data, indent=1) + "\n", ctx)