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