]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/directory.py
112595cd6ec74e44e187107dd459cb69cbf85070
[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, html
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         if not t:
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)
161
162         if t == "json":
163             return DirectoryJSONMetadata(ctx, self.node)
164         if t == "info":
165             return MoreInfo(self.node)
166         if t == "uri":
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)
172         if t == 'move-form':
173             return MoveForm(self.node)
174
175         raise WebError("GET directory: bad t=%s" % t)
176
177     def render_PUT(self, ctx):
178         req = IRequest(ctx)
179         t = get_arg(req, "t", "").strip()
180         replace = parse_replace_arg(get_arg(req, "replace", "true"))
181
182         if t == "mkdir":
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
186         if t == "uri":
187             if not replace:
188                 # they're trying to set_uri and that name is already occupied
189                 # (by us).
190                 raise ExistingChildError()
191             d = self.replace_me_with_a_childcap(req, self.client, replace)
192             # TODO: results
193             return d
194
195         raise WebError("PUT to a directory")
196
197     def render_POST(self, ctx):
198         req = IRequest(ctx)
199         t = get_arg(req, "t", "").strip()
200
201         if t == "mkdir":
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)
207         elif t == "mkdir-p":
208             # TODO: docs, tests
209             d = self._POST_mkdir_p(req)
210         elif t == "upload":
211             d = self._POST_upload(ctx) # this one needs the context
212         elif t == "uri":
213             d = self._POST_uri(req)
214         elif t == "delete" or t == "unlink":
215             d = self._POST_unlink(req)
216         elif t == "rename":
217             d = self._POST_rename(req)
218         elif t == "move":
219             d = self._POST_move(req)
220         elif t == "check":
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)
236         else:
237             raise WebError("POST to a directory with bad t=%s" % t)
238
239         when_done = get_arg(req, "when_done", None)
240         if when_done:
241             d.addCallback(lambda res: url.URL.fromString(when_done))
242         return d
243
244     def _POST_mkdir(self, req):
245         name = get_arg(req, "name", "")
246         if not 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"))
252         kids = {}
253         mt = get_mutable_type(get_format(req, None))
254         d = self.node.create_subdirectory(name, kids, overwrite=replace,
255                                           mutable_version=mt)
256         d.addCallback(lambda child: child.get_uri()) # TODO: urlencode
257         return d
258
259     def _POST_mkdir_with_children(self, req):
260         name = get_arg(req, "name", "")
261         if not 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"))
268         req.content.seek(0)
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,
273                                           mutable_version=mt)
274         d.addCallback(lambda child: child.get_uri()) # TODO: urlencode
275         return d
276
277     def _POST_mkdir_immutable(self, req):
278         name = get_arg(req, "name", "")
279         if not 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"))
286         req.content.seek(0)
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
291         return d
292
293     def _POST_mkdir_p(self, req):
294         path = get_arg(req, "path")
295         if not path:
296             raise WebError("mkdir-p requires a path")
297         path_ = tuple([seg.decode("utf-8") for seg in path.split('/') if seg ])
298         # TODO: replace
299         d = self._get_or_create_directories(self.node, path_)
300         d.addCallback(lambda node: node.get_uri())
301         return d
302
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")
309         if not path:
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:])
317         return d
318
319     def _POST_upload(self, ctx):
320         req = IRequest(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
326         if name is not None:
327             name = name.strip()
328         if not name:
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)
333         if "/" in name:
334             raise WebError("name= may not contain a slash", http.BAD_REQUEST)
335         assert isinstance(name, unicode)
336
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)
341
342         d = self.node.get(name)
343         def _maybe_got_node(node_or_failure):
344             if isinstance(node_or_failure, Failure):
345                 f = node_or_failure
346                 f.trap(NoSuchChildError)
347                 # create a placeholder which will see POST t=upload
348                 return PlaceHolderNodeHandler(self.client, self.node, name)
349             else:
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))
358         return d
359
360     def _POST_uri(self, req):
361         childcap = get_arg(req, "uri")
362         if not childcap:
363             raise WebError("set-uri requires a uri")
364         name = get_arg(req, "name")
365         if not 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"))
370
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)
377         return d
378
379     def _POST_unlink(self, req):
380         name = get_arg(req, "name")
381         if name is None:
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.
390             name = ''
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")
395         return d
396
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")
413
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.
417         if "/" in to_name:
418             raise WebError("to_name= may not contain a slash", http.BAD_REQUEST)
419
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")
423         return d
424
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)
437         if not to_name:
438             to_name = from_name
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
448         # Disallow slashes in both from_name and to_name, that would only
449         # cause confusion. t=move is only for moving things from the
450         # *current* directory into a second directory named by to_dir=
451         if "/" in from_name:
452             raise WebError("from_name= may not contain a slash",
453                            http.BAD_REQUEST)
454         if "/" in to_name:
455             raise WebError("to_name= may not contain a slash",
456                            http.BAD_REQUEST)
457
458         target_type = get_arg(req, "target_type", "name")
459         if target_type == "name":
460             d = self.node.get_child_at_path(to_dir)
461         elif target_type == "uri":
462             d = defer.succeed(self.client.create_node_from_uri(str(to_dir)))
463         else:
464             raise WebError("invalid target_type parameter", http.BAD_REQUEST)
465
466         def is_target_node_usable(target_node):
467             if not IDirectoryNode.providedBy(target_node):
468                 raise WebError("to_dir is not a directory", http.BAD_REQUEST)
469             return target_node
470         d.addCallback(is_target_node_usable)
471         d.addCallback(lambda new_parent:
472                       self.node.move_child_to(from_name, new_parent,
473                                               to_name, replace))
474         d.addCallback(lambda res: "thing moved")
475         return d
476
477     def _maybe_literal(self, res, Results_Class):
478         if res:
479             return Results_Class(self.client, res)
480         return LiteralCheckResultsRenderer(self.client)
481
482     def _POST_check(self, req):
483         # check this directory
484         verify = boolean_of_arg(get_arg(req, "verify", "false"))
485         repair = boolean_of_arg(get_arg(req, "repair", "false"))
486         add_lease = boolean_of_arg(get_arg(req, "add-lease", "false"))
487         if repair:
488             d = self.node.check_and_repair(Monitor(), verify, add_lease)
489             d.addCallback(self._maybe_literal, CheckAndRepairResultsRenderer)
490         else:
491             d = self.node.check(Monitor(), verify, add_lease)
492             d.addCallback(self._maybe_literal, CheckResultsRenderer)
493         return d
494
495     def _start_operation(self, monitor, renderer, ctx):
496         table = IOpHandleTable(ctx)
497         table.add_monitor(ctx, monitor, renderer)
498         return table.redirect_to(ctx)
499
500     def _POST_start_deep_check(self, ctx):
501         # check this directory and everything reachable from it
502         if not get_arg(ctx, "ophandle"):
503             raise NeedOperationHandleError("slow operation requires ophandle=")
504         verify = boolean_of_arg(get_arg(ctx, "verify", "false"))
505         repair = boolean_of_arg(get_arg(ctx, "repair", "false"))
506         add_lease = boolean_of_arg(get_arg(ctx, "add-lease", "false"))
507         if repair:
508             monitor = self.node.start_deep_check_and_repair(verify, add_lease)
509             renderer = DeepCheckAndRepairResultsRenderer(self.client, monitor)
510         else:
511             monitor = self.node.start_deep_check(verify, add_lease)
512             renderer = DeepCheckResultsRenderer(self.client, monitor)
513         return self._start_operation(monitor, renderer, ctx)
514
515     def _POST_stream_deep_check(self, ctx):
516         verify = boolean_of_arg(get_arg(ctx, "verify", "false"))
517         repair = boolean_of_arg(get_arg(ctx, "repair", "false"))
518         add_lease = boolean_of_arg(get_arg(ctx, "add-lease", "false"))
519         walker = DeepCheckStreamer(ctx, self.node, verify, repair, add_lease)
520         monitor = self.node.deep_traverse(walker)
521         walker.setMonitor(monitor)
522         # register to hear stopProducing. The walker ignores pauseProducing.
523         IRequest(ctx).registerProducer(walker, True)
524         d = monitor.when_done()
525         def _done(res):
526             IRequest(ctx).unregisterProducer()
527             return res
528         d.addBoth(_done)
529         def _cancelled(f):
530             f.trap(OperationCancelledError)
531             return "Operation Cancelled"
532         d.addErrback(_cancelled)
533         def _error(f):
534             # signal the error as a non-JSON "ERROR:" line, plus exception
535             msg = "ERROR: %s(%s)\n" % (f.value.__class__.__name__,
536                                        ", ".join([str(a) for a in f.value.args]))
537             msg += str(f)
538             return msg
539         d.addErrback(_error)
540         return d
541
542     def _POST_start_manifest(self, ctx):
543         if not get_arg(ctx, "ophandle"):
544             raise NeedOperationHandleError("slow operation requires ophandle=")
545         monitor = self.node.build_manifest()
546         renderer = ManifestResults(self.client, monitor)
547         return self._start_operation(monitor, renderer, ctx)
548
549     def _POST_start_deep_size(self, ctx):
550         if not get_arg(ctx, "ophandle"):
551             raise NeedOperationHandleError("slow operation requires ophandle=")
552         monitor = self.node.start_deep_stats()
553         renderer = DeepSizeResults(self.client, monitor)
554         return self._start_operation(monitor, renderer, ctx)
555
556     def _POST_start_deep_stats(self, ctx):
557         if not get_arg(ctx, "ophandle"):
558             raise NeedOperationHandleError("slow operation requires ophandle=")
559         monitor = self.node.start_deep_stats()
560         renderer = DeepStatsResults(self.client, monitor)
561         return self._start_operation(monitor, renderer, ctx)
562
563     def _POST_stream_manifest(self, ctx):
564         walker = ManifestStreamer(ctx, self.node)
565         monitor = self.node.deep_traverse(walker)
566         walker.setMonitor(monitor)
567         # register to hear stopProducing. The walker ignores pauseProducing.
568         IRequest(ctx).registerProducer(walker, True)
569         d = monitor.when_done()
570         def _done(res):
571             IRequest(ctx).unregisterProducer()
572             return res
573         d.addBoth(_done)
574         def _cancelled(f):
575             f.trap(OperationCancelledError)
576             return "Operation Cancelled"
577         d.addErrback(_cancelled)
578         def _error(f):
579             # signal the error as a non-JSON "ERROR:" line, plus exception
580             msg = "ERROR: %s(%s)\n" % (f.value.__class__.__name__,
581                                        ", ".join([str(a) for a in f.value.args]))
582             msg += str(f)
583             return msg
584         d.addErrback(_error)
585         return d
586
587     def _POST_set_children(self, req):
588         replace = boolean_of_arg(get_arg(req, "replace", "true"))
589         req.content.seek(0)
590         body = req.content.read()
591         try:
592             children = simplejson.loads(body)
593         except ValueError, le:
594             le.args = tuple(le.args + (body,))
595             # TODO test handling of bad JSON
596             raise
597         cs = {}
598         for name, (file_or_dir, mddict) in children.iteritems():
599             name = unicode(name) # simplejson-2.0.1 returns str *or* unicode
600             writecap = mddict.get('rw_uri')
601             if writecap is not None:
602                 writecap = str(writecap)
603             readcap = mddict.get('ro_uri')
604             if readcap is not None:
605                 readcap = str(readcap)
606             cs[name] = (writecap, readcap, mddict.get('metadata'))
607         d = self.node.set_children(cs, replace)
608         d.addCallback(lambda res: "Okay so I did it.")
609         # TODO: results
610         return d
611
612 def abbreviated_dirnode(dirnode):
613     u = from_string_dirnode(dirnode.get_uri())
614     return u.abbrev_si()
615
616 SPACE = u"\u00A0"*2
617
618 class DirectoryAsHTML(rend.Page):
619     # The remainder of this class is to render the directory into
620     # human+browser -oriented HTML.
621     docFactory = getxmlfile("directory.xhtml")
622     addSlash = True
623
624     def __init__(self, node, default_mutable_format):
625         rend.Page.__init__(self)
626         self.node = node
627
628         assert default_mutable_format in (MDMF_VERSION, SDMF_VERSION)
629         self.default_mutable_format = default_mutable_format
630
631     def beforeRender(self, ctx):
632         # attempt to get the dirnode's children, stashing them (or the
633         # failure that results) for later use
634         d = self.node.list()
635         def _good(children):
636             # Deferreds don't optimize out tail recursion, and the way
637             # Nevow's flattener handles Deferreds doesn't take this into
638             # account. As a result, large lists of Deferreds that fire in the
639             # same turn (i.e. the output of defer.succeed) will cause a stack
640             # overflow. To work around this, we insert a turn break after
641             # every 100 items, using foolscap's fireEventually(). This gives
642             # the stack a chance to be popped. It would also work to put
643             # every item in its own turn, but that'd be a lot more
644             # inefficient. This addresses ticket #237, for which I was never
645             # able to create a failing unit test.
646             output = []
647             for i,item in enumerate(sorted(children.items())):
648                 if i % 100 == 0:
649                     output.append(fireEventually(item))
650                 else:
651                     output.append(item)
652             self.dirnode_children = output
653             return ctx
654         def _bad(f):
655             text, code = humanize_failure(f)
656             self.dirnode_children = None
657             self.dirnode_children_error = text
658             return ctx
659         d.addCallbacks(_good, _bad)
660         return d
661
662     def render_title(self, ctx, data):
663         si_s = abbreviated_dirnode(self.node)
664         header = ["Tahoe-LAFS - Directory SI=%s" % si_s]
665         if self.node.is_unknown():
666             header.append(" (unknown)")
667         elif not self.node.is_mutable():
668             header.append(" (immutable)")
669         elif self.node.is_readonly():
670             header.append(" (read-only)")
671         else:
672             header.append(" (modifiable)")
673         return ctx.tag[header]
674
675     def render_header(self, ctx, data):
676         si_s = abbreviated_dirnode(self.node)
677         header = ["Tahoe-LAFS Directory SI=", T.span(class_="data-chars")[si_s]]
678         if self.node.is_unknown():
679             header.append(" (unknown)")
680         elif not self.node.is_mutable():
681             header.append(" (immutable)")
682         elif self.node.is_readonly():
683             header.append(" (read-only)")
684         return ctx.tag[header]
685
686     def render_welcome(self, ctx, data):
687         link = get_root(ctx)
688         return ctx.tag[T.a(href=link)["Return to Welcome page"]]
689
690     def render_show_readonly(self, ctx, data):
691         if self.node.is_unknown() or self.node.is_readonly():
692             return ""
693         rocap = self.node.get_readonly_uri()
694         root = get_root(ctx)
695         uri_link = "%s/uri/%s/" % (root, urllib.quote(rocap))
696         return ctx.tag[T.a(href=uri_link)["Read-Only Version"]]
697
698     def render_try_children(self, ctx, data):
699         # if the dirnode can be retrived, render a table of children.
700         # Otherwise, render an apologetic error message.
701         if self.dirnode_children is not None:
702             return ctx.tag
703         else:
704             return T.div[T.p["Error reading directory:"],
705                          T.p[self.dirnode_children_error]]
706
707     def data_children(self, ctx, data):
708         return self.dirnode_children
709
710     def render_row(self, ctx, data):
711         name, (target, metadata) = data
712         name = name.encode("utf-8")
713         assert not isinstance(name, unicode)
714         nameurl = urllib.quote(name, safe="") # encode any slashes too
715
716         root = get_root(ctx)
717         here = "%s/uri/%s/" % (root, urllib.quote(self.node.get_uri()))
718         if self.node.is_unknown() or self.node.is_readonly():
719             unlink = "-"
720             rename = "-"
721             move = "-"
722         else:
723             # this creates a button which will cause our _POST_unlink method
724             # to be invoked, which unlinks the file and then redirects the
725             # browser back to this directory
726             unlink = T.form(action=here, method="post")[
727                 T.input(type='hidden', name='t', value='unlink'),
728                 T.input(type='hidden', name='name', value=name),
729                 T.input(type='hidden', name='when_done', value="."),
730                 T.input(type='submit', value='unlink', name="unlink"),
731                 ]
732
733             rename = T.form(action=here, method="get")[
734                 T.input(type='hidden', name='t', value='rename-form'),
735                 T.input(type='hidden', name='name', value=name),
736                 T.input(type='hidden', name='when_done', value="."),
737                 T.input(type='submit', value='rename', name="rename"),
738                 ]
739
740             move = T.form(action=here, method="get")[
741                 T.input(type='hidden', name='t', value='move-form'),
742                 T.input(type='hidden', name='name', value=name),
743                 T.input(type='hidden', name='when_done', value="."),
744                 T.input(type='submit', value='move', name="move"),
745                 ]
746
747         ctx.fillSlots("unlink", unlink)
748         ctx.fillSlots("rename", rename)
749         ctx.fillSlots("move", move)
750
751         times = []
752         linkcrtime = metadata.get('tahoe', {}).get("linkcrtime")
753         if linkcrtime is not None:
754             times.append("lcr: " + time_format.iso_local(linkcrtime))
755         else:
756             # For backwards-compatibility with links last modified by Tahoe < 1.4.0:
757             if "ctime" in metadata:
758                 ctime = time_format.iso_local(metadata["ctime"])
759                 times.append("c: " + ctime)
760         linkmotime = metadata.get('tahoe', {}).get("linkmotime")
761         if linkmotime is not None:
762             if times:
763                 times.append(T.br())
764             times.append("lmo: " + time_format.iso_local(linkmotime))
765         else:
766             # For backwards-compatibility with links last modified by Tahoe < 1.4.0:
767             if "mtime" in metadata:
768                 mtime = time_format.iso_local(metadata["mtime"])
769                 if times:
770                     times.append(T.br())
771                 times.append("m: " + mtime)
772         ctx.fillSlots("times", times)
773
774         assert IFilesystemNode.providedBy(target), target
775         target_uri = target.get_uri() or ""
776         quoted_uri = urllib.quote(target_uri, safe="") # escape slashes too
777
778         if IMutableFileNode.providedBy(target):
779             # to prevent javascript in displayed .html files from stealing a
780             # secret directory URI from the URL, send the browser to a URI-based
781             # page that doesn't know about the directory at all
782             dlurl = "%s/file/%s/@@named=/%s" % (root, quoted_uri, nameurl)
783
784             ctx.fillSlots("filename",
785                           T.a(href=dlurl)[html.escape(name)])
786             ctx.fillSlots("type", "SSK")
787
788             ctx.fillSlots("size", "?")
789
790             info_link = "%s/uri/%s?t=info" % (root, quoted_uri)
791
792         elif IImmutableFileNode.providedBy(target):
793             dlurl = "%s/file/%s/@@named=/%s" % (root, quoted_uri, nameurl)
794
795             ctx.fillSlots("filename",
796                           T.a(href=dlurl)[html.escape(name)])
797             ctx.fillSlots("type", "FILE")
798
799             ctx.fillSlots("size", target.get_size())
800
801             info_link = "%s/uri/%s?t=info" % (root, quoted_uri)
802
803         elif IDirectoryNode.providedBy(target):
804             # directory
805             uri_link = "%s/uri/%s/" % (root, urllib.quote(target_uri))
806             ctx.fillSlots("filename",
807                           T.a(href=uri_link)[html.escape(name)])
808             if not target.is_mutable():
809                 dirtype = "DIR-IMM"
810             elif target.is_readonly():
811                 dirtype = "DIR-RO"
812             else:
813                 dirtype = "DIR"
814             ctx.fillSlots("type", dirtype)
815             ctx.fillSlots("size", "-")
816             info_link = "%s/uri/%s/?t=info" % (root, quoted_uri)
817
818         elif isinstance(target, ProhibitedNode):
819             ctx.fillSlots("filename", T.strike[name])
820             if IDirectoryNode.providedBy(target.wrapped_node):
821                 blacklisted_type = "DIR-BLACKLISTED"
822             else:
823                 blacklisted_type = "BLACKLISTED"
824             ctx.fillSlots("type", blacklisted_type)
825             ctx.fillSlots("size", "-")
826             info_link = None
827             ctx.fillSlots("info", ["Access Prohibited:", T.br, target.reason])
828
829         else:
830             # unknown
831             ctx.fillSlots("filename", html.escape(name))
832             if target.get_write_uri() is not None:
833                 unknowntype = "?"
834             elif not self.node.is_mutable() or target.is_alleged_immutable():
835                 unknowntype = "?-IMM"
836             else:
837                 unknowntype = "?-RO"
838             ctx.fillSlots("type", unknowntype)
839             ctx.fillSlots("size", "-")
840             # use a directory-relative info link, so we can extract both the
841             # writecap and the readcap
842             info_link = "%s?t=info" % urllib.quote(name)
843
844         if info_link:
845             ctx.fillSlots("info", T.a(href=info_link)["More Info"])
846
847         return ctx.tag
848
849     # XXX: similar to render_upload_form and render_mkdir_form in root.py.
850     def render_forms(self, ctx, data):
851         forms = []
852
853         if self.node.is_readonly():
854             return T.div["No upload forms: directory is read-only"]
855         if self.dirnode_children is None:
856             return T.div["No upload forms: directory is unreadable"]
857
858         mkdir_sdmf = T.input(type='radio', name='format',
859                              value='sdmf', id='mkdir-sdmf',
860                              checked='checked')
861         mkdir_mdmf = T.input(type='radio', name='format',
862                              value='mdmf', id='mkdir-mdmf')
863
864         mkdir_form = T.form(action=".", method="post",
865                             enctype="multipart/form-data")[
866             T.fieldset[
867             T.input(type="hidden", name="t", value="mkdir"),
868             T.input(type="hidden", name="when_done", value="."),
869             T.legend(class_="freeform-form-label")["Create a new directory in this directory"],
870             "New directory name:"+SPACE,
871             T.input(type="text", name="name"), SPACE,
872             T.input(type="submit", value="Create"), SPACE*2,
873             mkdir_sdmf, T.label(for_='mutable-directory-sdmf')[" SDMF"], SPACE,
874             mkdir_mdmf, T.label(for_='mutable-directory-mdmf')[" MDMF (experimental)"],
875             ]]
876         forms.append(T.div(class_="freeform-form")[mkdir_form])
877
878         upload_chk  = T.input(type='radio', name='format',
879                               value='chk', id='upload-chk',
880                               checked='checked')
881         upload_sdmf = T.input(type='radio', name='format',
882                               value='sdmf', id='upload-sdmf')
883         upload_mdmf = T.input(type='radio', name='format',
884                               value='mdmf', id='upload-mdmf')
885
886         upload_form = T.form(action=".", method="post",
887                              enctype="multipart/form-data")[
888             T.fieldset[
889             T.input(type="hidden", name="t", value="upload"),
890             T.input(type="hidden", name="when_done", value="."),
891             T.legend(class_="freeform-form-label")["Upload a file to this directory"],
892             "Choose a file to upload:"+SPACE,
893             T.input(type="file", name="file", class_="freeform-input-file"), SPACE,
894             T.input(type="submit", value="Upload"),                          SPACE*2,
895             upload_chk,  T.label(for_="upload-chk") [" Immutable"],          SPACE,
896             upload_sdmf, T.label(for_="upload-sdmf")[" SDMF"],               SPACE,
897             upload_mdmf, T.label(for_="upload-mdmf")[" MDMF (experimental)"],
898             ]]
899         forms.append(T.div(class_="freeform-form")[upload_form])
900
901         attach_form = T.form(action=".", method="post",
902                              enctype="multipart/form-data")[
903             T.fieldset[
904             T.input(type="hidden", name="t", value="uri"),
905             T.input(type="hidden", name="when_done", value="."),
906             T.legend(class_="freeform-form-label")["Add a link to a file or directory which is already in Tahoe-LAFS."],
907             "New child name:"+SPACE,
908             T.input(type="text", name="name"), SPACE*2,
909             "URI of new child:"+SPACE,
910             T.input(type="text", name="uri"), SPACE,
911             T.input(type="submit", value="Attach"),
912             ]]
913         forms.append(T.div(class_="freeform-form")[attach_form])
914         return forms
915
916     def render_results(self, ctx, data):
917         req = IRequest(ctx)
918         return get_arg(req, "results", "")
919
920
921 def DirectoryJSONMetadata(ctx, dirnode):
922     d = dirnode.list()
923     def _got(children):
924         kids = {}
925         for name, (childnode, metadata) in children.iteritems():
926             assert IFilesystemNode.providedBy(childnode), childnode
927             rw_uri = childnode.get_write_uri()
928             ro_uri = childnode.get_readonly_uri()
929             if IFileNode.providedBy(childnode):
930                 kiddata = ("filenode", {'size': childnode.get_size(),
931                                         'mutable': childnode.is_mutable(),
932                                         })
933                 if childnode.is_mutable():
934                     mutable_type = childnode.get_version()
935                     assert mutable_type in (SDMF_VERSION, MDMF_VERSION)
936                     if mutable_type == MDMF_VERSION:
937                         file_format = "MDMF"
938                     else:
939                         file_format = "SDMF"
940                 else:
941                     file_format = "CHK"
942                 kiddata[1]['format'] = file_format
943
944             elif IDirectoryNode.providedBy(childnode):
945                 kiddata = ("dirnode", {'mutable': childnode.is_mutable()})
946             else:
947                 kiddata = ("unknown", {})
948
949             kiddata[1]["metadata"] = metadata
950             if rw_uri:
951                 kiddata[1]["rw_uri"] = rw_uri
952             if ro_uri:
953                 kiddata[1]["ro_uri"] = ro_uri
954             verifycap = childnode.get_verify_cap()
955             if verifycap:
956                 kiddata[1]['verify_uri'] = verifycap.to_string()
957
958             kids[name] = kiddata
959
960         drw_uri = dirnode.get_write_uri()
961         dro_uri = dirnode.get_readonly_uri()
962         contents = { 'children': kids }
963         if dro_uri:
964             contents['ro_uri'] = dro_uri
965         if drw_uri:
966             contents['rw_uri'] = drw_uri
967         verifycap = dirnode.get_verify_cap()
968         if verifycap:
969             contents['verify_uri'] = verifycap.to_string()
970         contents['mutable'] = dirnode.is_mutable()
971         data = ("dirnode", contents)
972         json = simplejson.dumps(data, indent=1) + "\n"
973         return json
974     d.addCallback(_got)
975     d.addCallback(text_plain, ctx)
976     return d
977
978
979 def DirectoryURI(ctx, dirnode):
980     return text_plain(dirnode.get_uri(), ctx)
981
982 def DirectoryReadonlyURI(ctx, dirnode):
983     return text_plain(dirnode.get_readonly_uri(), ctx)
984
985 class RenameForm(rend.Page):
986     addSlash = True
987     docFactory = getxmlfile("rename-form.xhtml")
988
989     def render_title(self, ctx, data):
990         return ctx.tag["Directory SI=%s" % abbreviated_dirnode(self.original)]
991
992     def render_header(self, ctx, data):
993         header = ["Rename "
994                   "in directory SI=%s" % abbreviated_dirnode(self.original),
995                   ]
996
997         if self.original.is_readonly():
998             header.append(" (readonly!)")
999         header.append(":")
1000         return ctx.tag[header]
1001
1002     def render_when_done(self, ctx, data):
1003         return T.input(type="hidden", name="when_done", value=".")
1004
1005     def render_get_name(self, ctx, data):
1006         req = IRequest(ctx)
1007         name = get_arg(req, "name", "")
1008         ctx.tag.attributes['value'] = name
1009         return ctx.tag
1010
1011 class MoveForm(rend.Page):
1012     addSlash = True
1013     docFactory = getxmlfile("move-form.xhtml")
1014
1015     def render_title(self, ctx, data):
1016         return ctx.tag["Directory SI=%s" % abbreviated_dirnode(self.original)]
1017
1018     def render_header(self, ctx, data):
1019         header = ["Move "
1020                   "from directory SI=%s" % abbreviated_dirnode(self.original),
1021                   ]
1022
1023         if self.original.is_readonly():
1024             header.append(" (readonly!)")
1025         header.append(":")
1026         return ctx.tag[header]
1027
1028     def render_when_done(self, ctx, data):
1029         return T.input(type="hidden", name="when_done", value=".")
1030
1031     def render_get_name(self, ctx, data):
1032         req = IRequest(ctx)
1033         name = get_arg(req, "name", "")
1034         ctx.tag.attributes['value'] = name
1035         return ctx.tag
1036
1037
1038 class ManifestResults(rend.Page, ReloadMixin):
1039     docFactory = getxmlfile("manifest.xhtml")
1040
1041     def __init__(self, client, monitor):
1042         self.client = client
1043         self.monitor = monitor
1044
1045     def renderHTTP(self, ctx):
1046         req = inevow.IRequest(ctx)
1047         output = get_arg(req, "output", "html").lower()
1048         if output == "text":
1049             return self.text(req)
1050         if output == "json":
1051             return self.json(req)
1052         return rend.Page.renderHTTP(self, ctx)
1053
1054     def slashify_path(self, path):
1055         if not path:
1056             return ""
1057         return "/".join([p.encode("utf-8") for p in path])
1058
1059     def text(self, req):
1060         req.setHeader("content-type", "text/plain")
1061         lines = []
1062         is_finished = self.monitor.is_finished()
1063         lines.append("finished: " + {True: "yes", False: "no"}[is_finished])
1064         for (path, cap) in self.monitor.get_status()["manifest"]:
1065             lines.append(self.slashify_path(path) + " " + cap)
1066         return "\n".join(lines) + "\n"
1067
1068     def json(self, req):
1069         req.setHeader("content-type", "text/plain")
1070         m = self.monitor
1071         s = m.get_status()
1072
1073         if m.origin_si:
1074             origin_base32 = base32.b2a(m.origin_si)
1075         else:
1076             origin_base32 = ""
1077         status = { "stats": s["stats"],
1078                    "finished": m.is_finished(),
1079                    "origin": origin_base32,
1080                    }
1081         if m.is_finished():
1082             # don't return manifest/verifycaps/SIs unless the operation is
1083             # done, to save on CPU/memory (both here and in the HTTP client
1084             # who has to unpack the JSON). Tests show that the ManifestWalker
1085             # needs about 1092 bytes per item, the JSON we generate here
1086             # requires about 503 bytes per item, and some internal overhead
1087             # (perhaps transport-layer buffers in twisted.web?) requires an
1088             # additional 1047 bytes per item.
1089             status.update({ "manifest": s["manifest"],
1090                             "verifycaps": [i for i in s["verifycaps"]],
1091                             "storage-index": [i for i in s["storage-index"]],
1092                             })
1093             # simplejson doesn't know how to serialize a set. We use a
1094             # generator that walks the set rather than list(setofthing) to
1095             # save a small amount of memory (4B*len) and a moderate amount of
1096             # CPU.
1097         return simplejson.dumps(status, indent=1)
1098
1099     def _si_abbrev(self):
1100         si = self.monitor.origin_si
1101         if not si:
1102             return "<LIT>"
1103         return base32.b2a(si)[:6]
1104
1105     def render_title(self, ctx):
1106         return T.title["Manifest of SI=%s" % self._si_abbrev()]
1107
1108     def render_header(self, ctx):
1109         return T.p["Manifest of SI=%s" % self._si_abbrev()]
1110
1111     def data_items(self, ctx, data):
1112         return self.monitor.get_status()["manifest"]
1113
1114     def render_row(self, ctx, (path, cap)):
1115         ctx.fillSlots("path", self.slashify_path(path))
1116         root = get_root(ctx)
1117         # TODO: we need a clean consistent way to get the type of a cap string
1118         if cap:
1119             if cap.startswith("URI:CHK") or cap.startswith("URI:SSK"):
1120                 nameurl = urllib.quote(path[-1].encode("utf-8"))
1121                 uri_link = "%s/file/%s/@@named=/%s" % (root, urllib.quote(cap),
1122                                                        nameurl)
1123             else:
1124                 uri_link = "%s/uri/%s" % (root, urllib.quote(cap, safe=""))
1125             ctx.fillSlots("cap", T.a(href=uri_link)[cap])
1126         else:
1127             ctx.fillSlots("cap", "")
1128         return ctx.tag
1129
1130 class DeepSizeResults(rend.Page):
1131     def __init__(self, client, monitor):
1132         self.client = client
1133         self.monitor = monitor
1134
1135     def renderHTTP(self, ctx):
1136         req = inevow.IRequest(ctx)
1137         output = get_arg(req, "output", "html").lower()
1138         req.setHeader("content-type", "text/plain")
1139         if output == "json":
1140             return self.json(req)
1141         # plain text
1142         is_finished = self.monitor.is_finished()
1143         output = "finished: " + {True: "yes", False: "no"}[is_finished] + "\n"
1144         if is_finished:
1145             stats = self.monitor.get_status()
1146             total = (stats.get("size-immutable-files", 0)
1147                      + stats.get("size-mutable-files", 0)
1148                      + stats.get("size-directories", 0))
1149             output += "size: %d\n" % total
1150         return output
1151
1152     def json(self, req):
1153         status = {"finished": self.monitor.is_finished(),
1154                   "size": self.monitor.get_status(),
1155                   }
1156         return simplejson.dumps(status)
1157
1158 class DeepStatsResults(rend.Page):
1159     def __init__(self, client, monitor):
1160         self.client = client
1161         self.monitor = monitor
1162
1163     def renderHTTP(self, ctx):
1164         # JSON only
1165         inevow.IRequest(ctx).setHeader("content-type", "text/plain")
1166         s = self.monitor.get_status().copy()
1167         s["finished"] = self.monitor.is_finished()
1168         return simplejson.dumps(s, indent=1)
1169
1170 class ManifestStreamer(dirnode.DeepStats):
1171     implements(IPushProducer)
1172
1173     def __init__(self, ctx, origin):
1174         dirnode.DeepStats.__init__(self, origin)
1175         self.req = IRequest(ctx)
1176
1177     def setMonitor(self, monitor):
1178         self.monitor = monitor
1179     def pauseProducing(self):
1180         pass
1181     def resumeProducing(self):
1182         pass
1183     def stopProducing(self):
1184         self.monitor.cancel()
1185
1186     def add_node(self, node, path):
1187         dirnode.DeepStats.add_node(self, node, path)
1188         d = {"path": path,
1189              "cap": node.get_uri()}
1190
1191         if IDirectoryNode.providedBy(node):
1192             d["type"] = "directory"
1193         elif IFileNode.providedBy(node):
1194             d["type"] = "file"
1195         else:
1196             d["type"] = "unknown"
1197
1198         v = node.get_verify_cap()
1199         if v:
1200             v = v.to_string()
1201         d["verifycap"] = v or ""
1202
1203         r = node.get_repair_cap()
1204         if r:
1205             r = r.to_string()
1206         d["repaircap"] = r or ""
1207
1208         si = node.get_storage_index()
1209         if si:
1210             si = base32.b2a(si)
1211         d["storage-index"] = si or ""
1212
1213         j = simplejson.dumps(d, ensure_ascii=True)
1214         assert "\n" not in j
1215         self.req.write(j+"\n")
1216
1217     def finish(self):
1218         stats = dirnode.DeepStats.get_results(self)
1219         d = {"type": "stats",
1220              "stats": stats,
1221              }
1222         j = simplejson.dumps(d, ensure_ascii=True)
1223         assert "\n" not in j
1224         self.req.write(j+"\n")
1225         return ""
1226
1227 class DeepCheckStreamer(dirnode.DeepStats):
1228     implements(IPushProducer)
1229
1230     def __init__(self, ctx, origin, verify, repair, add_lease):
1231         dirnode.DeepStats.__init__(self, origin)
1232         self.req = IRequest(ctx)
1233         self.verify = verify
1234         self.repair = repair
1235         self.add_lease = add_lease
1236
1237     def setMonitor(self, monitor):
1238         self.monitor = monitor
1239     def pauseProducing(self):
1240         pass
1241     def resumeProducing(self):
1242         pass
1243     def stopProducing(self):
1244         self.monitor.cancel()
1245
1246     def add_node(self, node, path):
1247         dirnode.DeepStats.add_node(self, node, path)
1248         data = {"path": path,
1249                 "cap": node.get_uri()}
1250
1251         if IDirectoryNode.providedBy(node):
1252             data["type"] = "directory"
1253         elif IFileNode.providedBy(node):
1254             data["type"] = "file"
1255         else:
1256             data["type"] = "unknown"
1257
1258         v = node.get_verify_cap()
1259         if v:
1260             v = v.to_string()
1261         data["verifycap"] = v or ""
1262
1263         r = node.get_repair_cap()
1264         if r:
1265             r = r.to_string()
1266         data["repaircap"] = r or ""
1267
1268         si = node.get_storage_index()
1269         if si:
1270             si = base32.b2a(si)
1271         data["storage-index"] = si or ""
1272
1273         if self.repair:
1274             d = node.check_and_repair(self.monitor, self.verify, self.add_lease)
1275             d.addCallback(self.add_check_and_repair, data)
1276         else:
1277             d = node.check(self.monitor, self.verify, self.add_lease)
1278             d.addCallback(self.add_check, data)
1279         d.addCallback(self.write_line)
1280         return d
1281
1282     def add_check_and_repair(self, crr, data):
1283         data["check-and-repair-results"] = json_check_and_repair_results(crr)
1284         return data
1285
1286     def add_check(self, cr, data):
1287         data["check-results"] = json_check_results(cr)
1288         return data
1289
1290     def write_line(self, data):
1291         j = simplejson.dumps(data, ensure_ascii=True)
1292         assert "\n" not in j
1293         self.req.write(j+"\n")
1294
1295     def finish(self):
1296         stats = dirnode.DeepStats.get_results(self)
1297         d = {"type": "stats",
1298              "stats": stats,
1299              }
1300         j = simplejson.dumps(d, ensure_ascii=True)
1301         assert "\n" not in j
1302         self.req.write(j+"\n")
1303         return ""
1304
1305
1306 class UnknownNodeHandler(RenderMixin, rend.Page):
1307     def __init__(self, client, node, parentnode=None, name=None):
1308         rend.Page.__init__(self)
1309         assert node
1310         self.node = node
1311         self.parentnode = parentnode
1312         self.name = name
1313
1314     def render_GET(self, ctx):
1315         req = IRequest(ctx)
1316         t = get_arg(req, "t", "").strip()
1317         if t == "info":
1318             return MoreInfo(self.node)
1319         if t == "json":
1320             is_parent_known_immutable = self.parentnode and not self.parentnode.is_mutable()
1321             if self.parentnode and self.name:
1322                 d = self.parentnode.get_metadata_for(self.name)
1323             else:
1324                 d = defer.succeed(None)
1325             d.addCallback(lambda md: UnknownJSONMetadata(ctx, self.node, md, is_parent_known_immutable))
1326             return d
1327         raise WebError("GET unknown URI type: can only do t=info and t=json, not t=%s.\n"
1328                        "Using a webapi server that supports a later version of Tahoe "
1329                        "may help." % t)
1330
1331 def UnknownJSONMetadata(ctx, node, edge_metadata, is_parent_known_immutable):
1332     rw_uri = node.get_write_uri()
1333     ro_uri = node.get_readonly_uri()
1334     data = ("unknown", {})
1335     if ro_uri:
1336         data[1]['ro_uri'] = ro_uri
1337     if rw_uri:
1338         data[1]['rw_uri'] = rw_uri
1339         data[1]['mutable'] = True
1340     elif is_parent_known_immutable or node.is_alleged_immutable():
1341         data[1]['mutable'] = False
1342     # else we don't know whether it is mutable.
1343
1344     if edge_metadata is not None:
1345         data[1]['metadata'] = edge_metadata
1346     return text_plain(simplejson.dumps(data, indent=1) + "\n", ctx)