]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/directory.py
webapi #590: add streaming deep-check. Still need a CLI tool to use it.
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / web / directory.py
1
2 import simplejson
3 import urllib
4 import time
5
6 from zope.interface import implements
7 from twisted.internet import defer
8 from twisted.internet.interfaces import IPushProducer
9 from twisted.python.failure import Failure
10 from twisted.web import http, html
11 from nevow import url, rend, inevow, tags as T
12 from nevow.inevow import IRequest
13
14 from foolscap.eventual import fireEventually
15
16 from allmydata.util import base32
17 from allmydata.uri import from_string_dirnode
18 from allmydata.interfaces import IDirectoryNode, IFileNode, IMutableFileNode, \
19      ExistingChildError, NoSuchChildError
20 from allmydata.monitor import Monitor, OperationCancelledError
21 from allmydata import dirnode
22 from allmydata.web.common import text_plain, WebError, \
23      IClient, IOpHandleTable, NeedOperationHandleError, \
24      boolean_of_arg, get_arg, get_root, \
25      should_create_intermediate_directories, \
26      getxmlfile, RenderMixin
27 from allmydata.web.filenode import ReplaceMeMixin, \
28      FileNodeHandler, PlaceHolderNodeHandler
29 from allmydata.web.check_results import CheckResults, \
30      CheckAndRepairResults, DeepCheckResults, DeepCheckAndRepairResults
31 from allmydata.web.info import MoreInfo
32 from allmydata.web.operations import ReloadMixin
33 from allmydata.web.check_results import json_check_results, \
34      json_check_and_repair_results
35
36 class BlockingFileError(Exception):
37     # TODO: catch and transform
38     """We cannot auto-create a parent directory, because there is a file in
39     the way"""
40
41 def make_handler_for(node, parentnode=None, name=None):
42     if parentnode:
43         assert IDirectoryNode.providedBy(parentnode)
44     if IMutableFileNode.providedBy(node):
45         return FileNodeHandler(node, parentnode, name)
46     if IFileNode.providedBy(node):
47         return FileNodeHandler(node, parentnode, name)
48     if IDirectoryNode.providedBy(node):
49         return DirectoryNodeHandler(node, parentnode, name)
50     raise WebError("Cannot provide handler for '%s'" % node)
51
52 class DirectoryNodeHandler(RenderMixin, rend.Page, ReplaceMeMixin):
53     addSlash = True
54
55     def __init__(self, node, parentnode=None, name=None):
56         rend.Page.__init__(self)
57         assert node
58         self.node = node
59         self.parentnode = parentnode
60         self.name = name
61
62     def childFactory(self, ctx, name):
63         req = IRequest(ctx)
64         name = name.decode("utf-8")
65         d = self.node.get(name)
66         d.addBoth(self.got_child, ctx, name)
67         # got_child returns a handler resource: FileNodeHandler or
68         # DirectoryNodeHandler
69         return d
70
71     def got_child(self, node_or_failure, ctx, name):
72         DEBUG = False
73         if DEBUG: print "GOT_CHILD", name, node_or_failure
74         req = IRequest(ctx)
75         method = req.method
76         nonterminal = len(req.postpath) > 1
77         t = get_arg(req, "t", "").strip()
78         if isinstance(node_or_failure, Failure):
79             f = node_or_failure
80             f.trap(NoSuchChildError)
81             # No child by this name. What should we do about it?
82             if DEBUG: print "no child", name
83             if DEBUG: print "postpath", req.postpath
84             if nonterminal:
85                 if DEBUG: print " intermediate"
86                 if should_create_intermediate_directories(req):
87                     # create intermediate directories
88                     if DEBUG: print " making intermediate directory"
89                     d = self.node.create_empty_directory(name)
90                     d.addCallback(make_handler_for, self.node, name)
91                     return d
92             else:
93                 if DEBUG: print " terminal"
94                 # terminal node
95                 if (method,t) in [ ("POST","mkdir"), ("PUT","mkdir") ]:
96                     if DEBUG: print " making final directory"
97                     # final directory
98                     d = self.node.create_empty_directory(name)
99                     d.addCallback(make_handler_for, self.node, name)
100                     return d
101                 if (method,t) in ( ("PUT",""), ("PUT","uri"), ):
102                     if DEBUG: print " PUT, making leaf placeholder"
103                     # we were trying to find the leaf filenode (to put a new
104                     # file in its place), and it didn't exist. That's ok,
105                     # since that's the leaf node that we're about to create.
106                     # We make a dummy one, which will respond to the PUT
107                     # request by replacing itself.
108                     return PlaceHolderNodeHandler(self.node, name)
109             if DEBUG: print " 404"
110             # otherwise, we just return a no-such-child error
111             return rend.FourOhFour()
112
113         node = node_or_failure
114         if nonterminal and should_create_intermediate_directories(req):
115             if not IDirectoryNode.providedBy(node):
116                 # we would have put a new directory here, but there was a
117                 # file in the way.
118                 if DEBUG: print "blocking"
119                 raise WebError("Unable to create directory '%s': "
120                                "a file was in the way" % name,
121                                http.CONFLICT)
122         if DEBUG: print "good child"
123         return make_handler_for(node, self.node, name)
124
125     def render_DELETE(self, ctx):
126         assert self.parentnode and self.name
127         d = self.parentnode.delete(self.name)
128         d.addCallback(lambda res: self.node.get_uri())
129         return d
130
131     def render_GET(self, ctx):
132         client = IClient(ctx)
133         req = IRequest(ctx)
134         # This is where all of the directory-related ?t=* code goes.
135         t = get_arg(req, "t", "").strip()
136         if not t:
137             # render the directory as HTML, using the docFactory and Nevow's
138             # whole templating thing.
139             return DirectoryAsHTML(self.node)
140
141         if t == "json":
142             return DirectoryJSONMetadata(ctx, self.node)
143         if t == "info":
144             return MoreInfo(self.node)
145         if t == "uri":
146             return DirectoryURI(ctx, self.node)
147         if t == "readonly-uri":
148             return DirectoryReadonlyURI(ctx, self.node)
149         if t == 'rename-form':
150             return RenameForm(self.node)
151
152         raise WebError("GET directory: bad t=%s" % t)
153
154     def render_PUT(self, ctx):
155         req = IRequest(ctx)
156         t = get_arg(req, "t", "").strip()
157         replace = boolean_of_arg(get_arg(req, "replace", "true"))
158         if t == "mkdir":
159             # our job was done by the traversal/create-intermediate-directory
160             # process that got us here.
161             return text_plain(self.node.get_uri(), ctx) # TODO: urlencode
162         if t == "uri":
163             if not replace:
164                 # they're trying to set_uri and that name is already occupied
165                 # (by us).
166                 raise ExistingChildError()
167             d = self.replace_me_with_a_childcap(ctx, replace)
168             # TODO: results
169             return d
170
171         raise WebError("PUT to a directory")
172
173     def render_POST(self, ctx):
174         req = IRequest(ctx)
175         t = get_arg(req, "t", "").strip()
176
177         if t == "mkdir":
178             d = self._POST_mkdir(req)
179         elif t == "mkdir-p":
180             # TODO: docs, tests
181             d = self._POST_mkdir_p(req)
182         elif t == "upload":
183             d = self._POST_upload(ctx) # this one needs the context
184         elif t == "uri":
185             d = self._POST_uri(req)
186         elif t == "delete":
187             d = self._POST_delete(req)
188         elif t == "rename":
189             d = self._POST_rename(req)
190         elif t == "check":
191             d = self._POST_check(req)
192         elif t == "start-deep-check":
193             d = self._POST_start_deep_check(ctx)
194         elif t == "stream-deep-check":
195             d = self._POST_stream_deep_check(ctx)
196         elif t == "start-manifest":
197             d = self._POST_start_manifest(ctx)
198         elif t == "start-deep-size":
199             d = self._POST_start_deep_size(ctx)
200         elif t == "start-deep-stats":
201             d = self._POST_start_deep_stats(ctx)
202         elif t == "stream-manifest":
203             d = self._POST_stream_manifest(ctx)
204         elif t == "set_children":
205             # TODO: docs
206             d = self._POST_set_children(req)
207         else:
208             raise WebError("POST to a directory with bad t=%s" % t)
209
210         when_done = get_arg(req, "when_done", None)
211         if when_done:
212             d.addCallback(lambda res: url.URL.fromString(when_done))
213         return d
214
215     def _POST_mkdir(self, req):
216         name = get_arg(req, "name", "")
217         if not name:
218             # our job is done, it was handled by the code in got_child
219             # which created the final directory (i.e. us)
220             return defer.succeed(self.node.get_uri()) # TODO: urlencode
221         name = name.decode("utf-8")
222         replace = boolean_of_arg(get_arg(req, "replace", "true"))
223         d = self.node.create_empty_directory(name, overwrite=replace)
224         d.addCallback(lambda child: child.get_uri()) # TODO: urlencode
225         return d
226
227     def _POST_mkdir_p(self, req):
228         path = get_arg(req, "path")
229         if not path:
230             raise WebError("mkdir-p requires a path")
231         path_ = tuple([seg.decode("utf-8") for seg in path.split('/') if seg ])
232         # TODO: replace
233         d = self._get_or_create_directories(self.node, path_)
234         d.addCallback(lambda node: node.get_uri())
235         return d
236
237     def _get_or_create_directories(self, node, path):
238         if not IDirectoryNode.providedBy(node):
239             # unfortunately it is too late to provide the name of the
240             # blocking directory in the error message.
241             raise BlockingFileError("cannot create directory because there "
242                                     "is a file in the way")
243         if not path:
244             return defer.succeed(node)
245         d = node.get(path[0])
246         def _maybe_create(f):
247             f.trap(NoSuchChildError)
248             return node.create_empty_directory(path[0])
249         d.addErrback(_maybe_create)
250         d.addCallback(self._get_or_create_directories, path[1:])
251         return d
252
253     def _POST_upload(self, ctx):
254         req = IRequest(ctx)
255         charset = get_arg(req, "_charset", "utf-8")
256         contents = req.fields["file"]
257         assert contents.filename is None or isinstance(contents.filename, str)
258         name = get_arg(req, "name")
259         name = name or contents.filename
260         if name is not None:
261             name = name.strip()
262         if not name:
263             # this prohibts empty, missing, and all-whitespace filenames
264             raise WebError("upload requires a name")
265         assert isinstance(name, str)
266         name = name.decode(charset)
267         if "/" in name:
268             raise WebError("name= may not contain a slash", http.BAD_REQUEST)
269         assert isinstance(name, unicode)
270
271         # since POST /uri/path/file?t=upload is equivalent to
272         # POST /uri/path/dir?t=upload&name=foo, just do the same thing that
273         # childFactory would do. Things are cleaner if we only do a subset of
274         # them, though, so we don't do: d = self.childFactory(ctx, name)
275
276         d = self.node.get(name)
277         def _maybe_got_node(node_or_failure):
278             if isinstance(node_or_failure, Failure):
279                 f = node_or_failure
280                 f.trap(NoSuchChildError)
281                 # create a placeholder which will see POST t=upload
282                 return PlaceHolderNodeHandler(self.node, name)
283             else:
284                 node = node_or_failure
285                 return make_handler_for(node, self.node, name)
286         d.addBoth(_maybe_got_node)
287         # now we have a placeholder or a filenodehandler, and we can just
288         # delegate to it. We could return the resource back out of
289         # DirectoryNodeHandler.renderHTTP, and nevow would recurse into it,
290         # but the addCallback() that handles when_done= would break.
291         d.addCallback(lambda child: child.renderHTTP(ctx))
292         return d
293
294     def _POST_uri(self, req):
295         childcap = get_arg(req, "uri")
296         if not childcap:
297             raise WebError("set-uri requires a uri")
298         name = get_arg(req, "name")
299         if not name:
300             raise WebError("set-uri requires a name")
301         charset = get_arg(req, "_charset", "utf-8")
302         name = name.decode(charset)
303         replace = boolean_of_arg(get_arg(req, "replace", "true"))
304         d = self.node.set_uri(name, childcap, overwrite=replace)
305         d.addCallback(lambda res: childcap)
306         return d
307
308     def _POST_delete(self, req):
309         name = get_arg(req, "name")
310         if name is None:
311             # apparently an <input type="hidden" name="name" value="">
312             # won't show up in the resulting encoded form.. the 'name'
313             # field is completely missing. So to allow deletion of an
314             # empty file, we have to pretend that None means ''. The only
315             # downide of this is a slightly confusing error message if
316             # someone does a POST without a name= field. For our own HTML
317             # thisn't a big deal, because we create the 'delete' POST
318             # buttons ourselves.
319             name = ''
320         charset = get_arg(req, "_charset", "utf-8")
321         name = name.decode(charset)
322         d = self.node.delete(name)
323         d.addCallback(lambda res: "thing deleted")
324         return d
325
326     def _POST_rename(self, req):
327         charset = get_arg(req, "_charset", "utf-8")
328         from_name = get_arg(req, "from_name")
329         if from_name is not None:
330             from_name = from_name.strip()
331             from_name = from_name.decode(charset)
332             assert isinstance(from_name, unicode)
333         to_name = get_arg(req, "to_name")
334         if to_name is not None:
335             to_name = to_name.strip()
336             to_name = to_name.decode(charset)
337             assert isinstance(to_name, unicode)
338         if not from_name or not to_name:
339             raise WebError("rename requires from_name and to_name")
340         if from_name == to_name:
341             return defer.succeed("redundant rename")
342
343         # allow from_name to contain slashes, so they can fix names that were
344         # accidentally created with them. But disallow them in to_name, to
345         # discourage the practice.
346         if "/" in to_name:
347             raise WebError("to_name= may not contain a slash", http.BAD_REQUEST)
348
349         replace = boolean_of_arg(get_arg(req, "replace", "true"))
350         d = self.node.move_child_to(from_name, self.node, to_name, replace)
351         d.addCallback(lambda res: "thing renamed")
352         return d
353
354     def _POST_check(self, req):
355         # check this directory
356         verify = boolean_of_arg(get_arg(req, "verify", "false"))
357         repair = boolean_of_arg(get_arg(req, "repair", "false"))
358         if repair:
359             d = self.node.check_and_repair(Monitor(), verify)
360             d.addCallback(lambda res: CheckAndRepairResults(res))
361         else:
362             d = self.node.check(Monitor(), verify)
363             d.addCallback(lambda res: CheckResults(res))
364         return d
365
366     def _start_operation(self, monitor, renderer, ctx):
367         table = IOpHandleTable(ctx)
368         table.add_monitor(ctx, monitor, renderer)
369         return table.redirect_to(ctx)
370
371     def _POST_start_deep_check(self, ctx):
372         # check this directory and everything reachable from it
373         if not get_arg(ctx, "ophandle"):
374             raise NeedOperationHandleError("slow operation requires ophandle=")
375         verify = boolean_of_arg(get_arg(ctx, "verify", "false"))
376         repair = boolean_of_arg(get_arg(ctx, "repair", "false"))
377         if repair:
378             monitor = self.node.start_deep_check_and_repair(verify)
379             renderer = DeepCheckAndRepairResults(monitor)
380         else:
381             monitor = self.node.start_deep_check(verify)
382             renderer = DeepCheckResults(monitor)
383         return self._start_operation(monitor, renderer, ctx)
384
385     def _POST_stream_deep_check(self, ctx):
386         verify = boolean_of_arg(get_arg(ctx, "verify", "false"))
387         repair = boolean_of_arg(get_arg(ctx, "repair", "false"))
388         walker = DeepCheckStreamer(ctx, self.node, verify, repair)
389         monitor = self.node.deep_traverse(walker)
390         walker.setMonitor(monitor)
391         # register to hear stopProducing. The walker ignores pauseProducing.
392         IRequest(ctx).registerProducer(walker, True)
393         d = monitor.when_done()
394         def _done(res):
395             IRequest(ctx).unregisterProducer()
396             return res
397         d.addBoth(_done)
398         def _cancelled(f):
399             f.trap(OperationCancelledError)
400             return "Operation Cancelled"
401         d.addErrback(_cancelled)
402         return d
403
404     def _POST_start_manifest(self, ctx):
405         if not get_arg(ctx, "ophandle"):
406             raise NeedOperationHandleError("slow operation requires ophandle=")
407         monitor = self.node.build_manifest()
408         renderer = ManifestResults(monitor)
409         return self._start_operation(monitor, renderer, ctx)
410
411     def _POST_start_deep_size(self, ctx):
412         if not get_arg(ctx, "ophandle"):
413             raise NeedOperationHandleError("slow operation requires ophandle=")
414         monitor = self.node.start_deep_stats()
415         renderer = DeepSizeResults(monitor)
416         return self._start_operation(monitor, renderer, ctx)
417
418     def _POST_start_deep_stats(self, ctx):
419         if not get_arg(ctx, "ophandle"):
420             raise NeedOperationHandleError("slow operation requires ophandle=")
421         monitor = self.node.start_deep_stats()
422         renderer = DeepStatsResults(monitor)
423         return self._start_operation(monitor, renderer, ctx)
424
425     def _POST_stream_manifest(self, ctx):
426         walker = ManifestStreamer(ctx, self.node)
427         monitor = self.node.deep_traverse(walker)
428         walker.setMonitor(monitor)
429         # register to hear stopProducing. The walker ignores pauseProducing.
430         IRequest(ctx).registerProducer(walker, True)
431         d = monitor.when_done()
432         def _done(res):
433             IRequest(ctx).unregisterProducer()
434             return res
435         d.addBoth(_done)
436         def _cancelled(f):
437             f.trap(OperationCancelledError)
438             return "Operation Cancelled"
439         d.addErrback(_cancelled)
440         return d
441
442     def _POST_set_children(self, req):
443         replace = boolean_of_arg(get_arg(req, "replace", "true"))
444         req.content.seek(0)
445         body = req.content.read()
446         try:
447             children = simplejson.loads(body)
448         except ValueError, le:
449             le.args = tuple(le.args + (body,))
450             # TODO test handling of bad JSON
451             raise
452         cs = []
453         for name, (file_or_dir, mddict) in children.iteritems():
454             name = unicode(name) # simplejson-2.0.1 returns str *or* unicode
455             cap = str(mddict.get('rw_uri') or mddict.get('ro_uri'))
456             cs.append((name, cap, mddict.get('metadata')))
457         d = self.node.set_children(cs, replace)
458         d.addCallback(lambda res: "Okay so I did it.")
459         # TODO: results
460         return d
461
462 def abbreviated_dirnode(dirnode):
463     u = from_string_dirnode(dirnode.get_uri())
464     return u.abbrev_si()
465
466 class DirectoryAsHTML(rend.Page):
467     # The remainder of this class is to render the directory into
468     # human+browser -oriented HTML.
469     docFactory = getxmlfile("directory.xhtml")
470     addSlash = True
471
472     def __init__(self, node):
473         rend.Page.__init__(self)
474         self.node = node
475
476     def render_title(self, ctx, data):
477         si_s = abbreviated_dirnode(self.node)
478         header = ["Directory SI=%s" % si_s]
479         return ctx.tag[header]
480
481     def render_header(self, ctx, data):
482         si_s = abbreviated_dirnode(self.node)
483         header = ["Directory SI=%s" % si_s]
484         if self.node.is_readonly():
485             header.append(" (readonly)")
486         return ctx.tag[header]
487
488     def render_welcome(self, ctx, data):
489         link = get_root(ctx)
490         return T.div[T.a(href=link)["Return to Welcome page"]]
491
492     def render_show_readonly(self, ctx, data):
493         if self.node.is_readonly():
494             return ""
495         rocap = self.node.get_readonly_uri()
496         root = get_root(ctx)
497         uri_link = "%s/uri/%s/" % (root, urllib.quote(rocap))
498         return ctx.tag[T.a(href=uri_link)["Read-Only Version"]]
499
500     def data_children(self, ctx, data):
501         d = self.node.list()
502         d.addCallback(lambda dict: sorted(dict.items()))
503         def _stall_some(items):
504             # Deferreds don't optimize out tail recursion, and the way
505             # Nevow's flattener handles Deferreds doesn't take this into
506             # account. As a result, large lists of Deferreds that fire in the
507             # same turn (i.e. the output of defer.succeed) will cause a stack
508             # overflow. To work around this, we insert a turn break after
509             # every 100 items, using foolscap's fireEventually(). This gives
510             # the stack a chance to be popped. It would also work to put
511             # every item in its own turn, but that'd be a lot more
512             # inefficient. This addresses ticket #237, for which I was never
513             # able to create a failing unit test.
514             output = []
515             for i,item in enumerate(items):
516                 if i % 100 == 0:
517                     output.append(fireEventually(item))
518                 else:
519                     output.append(item)
520             return output
521         d.addCallback(_stall_some)
522         return d
523
524     def render_row(self, ctx, data):
525         name, (target, metadata) = data
526         name = name.encode("utf-8")
527         assert not isinstance(name, unicode)
528         nameurl = urllib.quote(name, safe="") # encode any slashes too
529
530         root = get_root(ctx)
531         here = "%s/uri/%s/" % (root, urllib.quote(self.node.get_uri()))
532         if self.node.is_readonly():
533             delete = "-"
534             rename = "-"
535         else:
536             # this creates a button which will cause our child__delete method
537             # to be invoked, which deletes the file and then redirects the
538             # browser back to this directory
539             delete = T.form(action=here, method="post")[
540                 T.input(type='hidden', name='t', value='delete'),
541                 T.input(type='hidden', name='name', value=name),
542                 T.input(type='hidden', name='when_done', value="."),
543                 T.input(type='submit', value='del', name="del"),
544                 ]
545
546             rename = T.form(action=here, method="get")[
547                 T.input(type='hidden', name='t', value='rename-form'),
548                 T.input(type='hidden', name='name', value=name),
549                 T.input(type='hidden', name='when_done', value="."),
550                 T.input(type='submit', value='rename', name="rename"),
551                 ]
552
553         ctx.fillSlots("delete", delete)
554         ctx.fillSlots("rename", rename)
555
556         times = []
557         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
558         if "ctime" in metadata:
559             ctime = time.strftime(TIME_FORMAT,
560                                   time.localtime(metadata["ctime"]))
561             times.append("c: " + ctime)
562         if "mtime" in metadata:
563             mtime = time.strftime(TIME_FORMAT,
564                                   time.localtime(metadata["mtime"]))
565             if times:
566                 times.append(T.br())
567                 times.append("m: " + mtime)
568         ctx.fillSlots("times", times)
569
570         assert (IFileNode.providedBy(target)
571                 or IDirectoryNode.providedBy(target)
572                 or IMutableFileNode.providedBy(target)), target
573
574         quoted_uri = urllib.quote(target.get_uri())
575
576         if IMutableFileNode.providedBy(target):
577             # to prevent javascript in displayed .html files from stealing a
578             # secret directory URI from the URL, send the browser to a URI-based
579             # page that doesn't know about the directory at all
580             dlurl = "%s/file/%s/@@named=/%s" % (root, quoted_uri, nameurl)
581
582             ctx.fillSlots("filename",
583                           T.a(href=dlurl)[html.escape(name)])
584             ctx.fillSlots("type", "SSK")
585
586             ctx.fillSlots("size", "?")
587
588             info_link = "%s/uri/%s?t=info" % (root, quoted_uri)
589
590         elif IFileNode.providedBy(target):
591             dlurl = "%s/file/%s/@@named=/%s" % (root, quoted_uri, nameurl)
592
593             ctx.fillSlots("filename",
594                           T.a(href=dlurl)[html.escape(name)])
595             ctx.fillSlots("type", "FILE")
596
597             ctx.fillSlots("size", target.get_size())
598
599             info_link = "%s/uri/%s?t=info" % (root, quoted_uri)
600
601         elif IDirectoryNode.providedBy(target):
602             # directory
603             uri_link = "%s/uri/%s/" % (root, urllib.quote(target.get_uri()))
604             ctx.fillSlots("filename",
605                           T.a(href=uri_link)[html.escape(name)])
606             if target.is_readonly():
607                 dirtype = "DIR-RO"
608             else:
609                 dirtype = "DIR"
610             ctx.fillSlots("type", dirtype)
611             ctx.fillSlots("size", "-")
612             info_link = "%s/uri/%s/?t=info" % (root, quoted_uri)
613
614         ctx.fillSlots("info", T.a(href=info_link)["More Info"])
615
616         return ctx.tag
617
618     def render_forms(self, ctx, data):
619         forms = []
620
621         if self.node.is_readonly():
622             forms.append(T.div["No upload forms: directory is read-only"])
623             return forms
624
625         mkdir = T.form(action=".", method="post",
626                        enctype="multipart/form-data")[
627             T.fieldset[
628             T.input(type="hidden", name="t", value="mkdir"),
629             T.input(type="hidden", name="when_done", value="."),
630             T.legend(class_="freeform-form-label")["Create a new directory"],
631             "New directory name: ",
632             T.input(type="text", name="name"), " ",
633             T.input(type="submit", value="Create"),
634             ]]
635         forms.append(T.div(class_="freeform-form")[mkdir])
636
637         upload = T.form(action=".", method="post",
638                         enctype="multipart/form-data")[
639             T.fieldset[
640             T.input(type="hidden", name="t", value="upload"),
641             T.input(type="hidden", name="when_done", value="."),
642             T.legend(class_="freeform-form-label")["Upload a file to this directory"],
643             "Choose a file to upload: ",
644             T.input(type="file", name="file", class_="freeform-input-file"),
645             " ",
646             T.input(type="submit", value="Upload"),
647             " Mutable?:",
648             T.input(type="checkbox", name="mutable"),
649             ]]
650         forms.append(T.div(class_="freeform-form")[upload])
651
652         mount = T.form(action=".", method="post",
653                         enctype="multipart/form-data")[
654             T.fieldset[
655             T.input(type="hidden", name="t", value="uri"),
656             T.input(type="hidden", name="when_done", value="."),
657             T.legend(class_="freeform-form-label")["Attach a file or directory"
658                                                    " (by URI) to this"
659                                                    " directory"],
660             "New child name: ",
661             T.input(type="text", name="name"), " ",
662             "URI of new child: ",
663             T.input(type="text", name="uri"), " ",
664             T.input(type="submit", value="Attach"),
665             ]]
666         forms.append(T.div(class_="freeform-form")[mount])
667         return forms
668
669     def render_results(self, ctx, data):
670         req = IRequest(ctx)
671         return get_arg(req, "results", "")
672
673
674 def DirectoryJSONMetadata(ctx, dirnode):
675     d = dirnode.list()
676     def _got(children):
677         kids = {}
678         for name, (childnode, metadata) in children.iteritems():
679             if childnode.is_readonly():
680                 rw_uri = None
681                 ro_uri = childnode.get_uri()
682             else:
683                 rw_uri = childnode.get_uri()
684                 ro_uri = childnode.get_readonly_uri()
685             if IFileNode.providedBy(childnode):
686                 kiddata = ("filenode", {'size': childnode.get_size(),
687                                         'metadata': metadata,
688                                         })
689             else:
690                 assert IDirectoryNode.providedBy(childnode), (childnode,
691                                                               children,)
692                 kiddata = ("dirnode", {'metadata': metadata})
693             if ro_uri:
694                 kiddata[1]["ro_uri"] = ro_uri
695             if rw_uri:
696                 kiddata[1]["rw_uri"] = rw_uri
697             verifycap = childnode.get_verify_cap()
698             if verifycap:
699                 kiddata[1]['verify_uri'] = verifycap.to_string()
700             kiddata[1]['mutable'] = childnode.is_mutable()
701             kids[name] = kiddata
702         if dirnode.is_readonly():
703             drw_uri = None
704             dro_uri = dirnode.get_uri()
705         else:
706             drw_uri = dirnode.get_uri()
707             dro_uri = dirnode.get_readonly_uri()
708         contents = { 'children': kids }
709         if dro_uri:
710             contents['ro_uri'] = dro_uri
711         if drw_uri:
712             contents['rw_uri'] = drw_uri
713         verifycap = dirnode.get_verify_cap()
714         if verifycap:
715             contents['verify_uri'] = verifycap.to_string()
716         contents['mutable'] = dirnode.is_mutable()
717         data = ("dirnode", contents)
718         return simplejson.dumps(data, indent=1) + "\n"
719     d.addCallback(_got)
720     d.addCallback(text_plain, ctx)
721     return d
722
723
724
725 def DirectoryURI(ctx, dirnode):
726     return text_plain(dirnode.get_uri(), ctx)
727
728 def DirectoryReadonlyURI(ctx, dirnode):
729     return text_plain(dirnode.get_readonly_uri(), ctx)
730
731 class RenameForm(rend.Page):
732     addSlash = True
733     docFactory = getxmlfile("rename-form.xhtml")
734
735     def render_title(self, ctx, data):
736         return ctx.tag["Directory SI=%s" % abbreviated_dirnode(self.original)]
737
738     def render_header(self, ctx, data):
739         header = ["Rename "
740                   "in directory SI=%s" % abbreviated_dirnode(self.original),
741                   ]
742
743         if self.original.is_readonly():
744             header.append(" (readonly!)")
745         header.append(":")
746         return ctx.tag[header]
747
748     def render_when_done(self, ctx, data):
749         return T.input(type="hidden", name="when_done", value=".")
750
751     def render_get_name(self, ctx, data):
752         req = IRequest(ctx)
753         name = get_arg(req, "name", "")
754         ctx.tag.attributes['value'] = name
755         return ctx.tag
756
757
758 class ManifestResults(rend.Page, ReloadMixin):
759     docFactory = getxmlfile("manifest.xhtml")
760
761     def __init__(self, monitor):
762         self.monitor = monitor
763
764     def renderHTTP(self, ctx):
765         output = get_arg(inevow.IRequest(ctx), "output", "html").lower()
766         if output == "text":
767             return self.text(ctx)
768         if output == "json":
769             return self.json(ctx)
770         return rend.Page.renderHTTP(self, ctx)
771
772     def slashify_path(self, path):
773         if not path:
774             return ""
775         return "/".join([p.encode("utf-8") for p in path])
776
777     def text(self, ctx):
778         inevow.IRequest(ctx).setHeader("content-type", "text/plain")
779         lines = []
780         is_finished = self.monitor.is_finished()
781         lines.append("finished: " + {True: "yes", False: "no"}[is_finished])
782         for (path, cap) in self.monitor.get_status()["manifest"]:
783             lines.append(self.slashify_path(path) + " " + cap)
784         return "\n".join(lines) + "\n"
785
786     def json(self, ctx):
787         inevow.IRequest(ctx).setHeader("content-type", "text/plain")
788         m = self.monitor
789         s = m.get_status()
790
791         status = { "stats": s["stats"],
792                    "finished": m.is_finished(),
793                    "origin": base32.b2a(m.origin_si),
794                    }
795         if m.is_finished():
796             # don't return manifest/verifycaps/SIs unless the operation is
797             # done, to save on CPU/memory (both here and in the HTTP client
798             # who has to unpack the JSON). Tests show that the ManifestWalker
799             # needs about 1092 bytes per item, the JSON we generate here
800             # requires about 503 bytes per item, and some internal overhead
801             # (perhaps transport-layer buffers in twisted.web?) requires an
802             # additional 1047 bytes per item.
803             status.update({ "manifest": s["manifest"],
804                             "verifycaps": [i for i in s["verifycaps"]],
805                             "storage-index": [i for i in s["storage-index"]],
806                             })
807             # simplejson doesn't know how to serialize a set. We use a
808             # generator that walks the set rather than list(setofthing) to
809             # save a small amount of memory (4B*len) and a moderate amount of
810             # CPU.
811         return simplejson.dumps(status, indent=1)
812
813     def _si_abbrev(self):
814         return base32.b2a(self.monitor.origin_si)[:6]
815
816     def render_title(self, ctx):
817         return T.title["Manifest of SI=%s" % self._si_abbrev()]
818
819     def render_header(self, ctx):
820         return T.p["Manifest of SI=%s" % self._si_abbrev()]
821
822     def data_items(self, ctx, data):
823         return self.monitor.get_status()["manifest"]
824
825     def render_row(self, ctx, (path, cap)):
826         ctx.fillSlots("path", self.slashify_path(path))
827         root = get_root(ctx)
828         # TODO: we need a clean consistent way to get the type of a cap string
829         if cap.startswith("URI:CHK") or cap.startswith("URI:SSK"):
830             nameurl = urllib.quote(path[-1].encode("utf-8"))
831             uri_link = "%s/file/%s/@@named=/%s" % (root, urllib.quote(cap),
832                                                    nameurl)
833         else:
834             uri_link = "%s/uri/%s" % (root, urllib.quote(cap))
835         ctx.fillSlots("cap", T.a(href=uri_link)[cap])
836         return ctx.tag
837
838 class DeepSizeResults(rend.Page):
839     def __init__(self, monitor):
840         self.monitor = monitor
841
842     def renderHTTP(self, ctx):
843         output = get_arg(inevow.IRequest(ctx), "output", "html").lower()
844         inevow.IRequest(ctx).setHeader("content-type", "text/plain")
845         if output == "json":
846             return self.json(ctx)
847         # plain text
848         is_finished = self.monitor.is_finished()
849         output = "finished: " + {True: "yes", False: "no"}[is_finished] + "\n"
850         if is_finished:
851             stats = self.monitor.get_status()
852             total = (stats.get("size-immutable-files", 0)
853                      + stats.get("size-mutable-files", 0)
854                      + stats.get("size-directories", 0))
855             output += "size: %d\n" % total
856         return output
857
858     def json(self, ctx):
859         status = {"finished": self.monitor.is_finished(),
860                   "size": self.monitor.get_status(),
861                   }
862         return simplejson.dumps(status)
863
864 class DeepStatsResults(rend.Page):
865     def __init__(self, monitor):
866         self.monitor = monitor
867
868     def renderHTTP(self, ctx):
869         # JSON only
870         inevow.IRequest(ctx).setHeader("content-type", "text/plain")
871         s = self.monitor.get_status().copy()
872         s["finished"] = self.monitor.is_finished()
873         return simplejson.dumps(s, indent=1)
874
875 class ManifestStreamer(dirnode.DeepStats):
876     implements(IPushProducer)
877
878     def __init__(self, ctx, origin):
879         dirnode.DeepStats.__init__(self, origin)
880         self.req = IRequest(ctx)
881
882     def setMonitor(self, monitor):
883         self.monitor = monitor
884     def pauseProducing(self):
885         pass
886     def resumeProducing(self):
887         pass
888     def stopProducing(self):
889         self.monitor.cancel()
890
891     def add_node(self, node, path):
892         dirnode.DeepStats.add_node(self, node, path)
893         d = {"path": path,
894              "cap": node.get_uri()}
895
896         if IDirectoryNode.providedBy(node):
897             d["type"] = "directory"
898         else:
899             d["type"] = "file"
900
901         v = node.get_verify_cap()
902         if v:
903             v = v.to_string()
904         d["verifycap"] = v
905
906         r = node.get_repair_cap()
907         if r:
908             r = r.to_string()
909         d["repaircap"] = r
910
911         si = node.get_storage_index()
912         if si:
913             si = base32.b2a(si)
914         d["storage-index"] = si
915
916         j = simplejson.dumps(d, ensure_ascii=True)
917         assert "\n" not in j
918         self.req.write(j+"\n")
919
920     def finish(self):
921         stats = dirnode.DeepStats.get_results(self)
922         d = {"type": "stats",
923              "stats": stats,
924              }
925         j = simplejson.dumps(d, ensure_ascii=True)
926         assert "\n" not in j
927         self.req.write(j+"\n")
928         return ""
929
930 class DeepCheckStreamer(dirnode.DeepStats):
931     implements(IPushProducer)
932
933     def __init__(self, ctx, origin, verify, repair):
934         dirnode.DeepStats.__init__(self, origin)
935         self.req = IRequest(ctx)
936         self.verify = verify
937         self.repair = repair
938
939     def setMonitor(self, monitor):
940         self.monitor = monitor
941     def pauseProducing(self):
942         pass
943     def resumeProducing(self):
944         pass
945     def stopProducing(self):
946         self.monitor.cancel()
947
948     def add_node(self, node, path):
949         dirnode.DeepStats.add_node(self, node, path)
950         data = {"path": path,
951                 "cap": node.get_uri()}
952
953         if IDirectoryNode.providedBy(node):
954             data["type"] = "directory"
955         else:
956             data["type"] = "file"
957
958         v = node.get_verify_cap()
959         if v:
960             v = v.to_string()
961         data["verifycap"] = v
962
963         r = node.get_repair_cap()
964         if r:
965             r = r.to_string()
966         data["repaircap"] = r
967
968         si = node.get_storage_index()
969         if si:
970             si = base32.b2a(si)
971         data["storage-index"] = si
972
973         if self.repair:
974             d = node.check_and_repair(self.monitor, self.verify)
975             d.addCallback(self.add_check_and_repair, data)
976         else:
977             d = node.check(self.monitor, self.verify)
978             d.addCallback(self.add_check, data)
979         d.addCallback(self.write_line)
980         return d
981
982     def add_check_and_repair(self, crr, data):
983         data["check-and-repair-results"] = json_check_and_repair_results(crr)
984         return data
985
986     def add_check(self, cr, data):
987         data["check-results"] = json_check_results(cr)
988         return data
989
990     def write_line(self, data):
991         j = simplejson.dumps(data, ensure_ascii=True)
992         assert "\n" not in j
993         self.req.write(j+"\n")
994
995     def finish(self):
996         stats = dirnode.DeepStats.get_results(self)
997         d = {"type": "stats",
998              "stats": stats,
999              }
1000         j = simplejson.dumps(d, ensure_ascii=True)
1001         assert "\n" not in j
1002         self.req.write(j+"\n")
1003         return ""