]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/webish.py
add GET /uri/URI/?t=deep-size, to compute the total size of immutable files reachable...
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / webish.py
1
2 import time, os.path
3 from twisted.application import service, strports, internet
4 from twisted.web import static, resource, server, html, http
5 from twisted.internet import defer, address
6 from twisted.internet.interfaces import IConsumer
7 from nevow import inevow, rend, appserver, url, tags as T
8 from nevow.static import File as nevow_File # TODO: merge with static.File?
9 from allmydata.util import fileutil, idlib, log
10 import simplejson
11 from allmydata.interfaces import IDownloadTarget, IDirectoryNode, IFileNode, \
12      IMutableFileNode
13 import allmydata # to display import path
14 from allmydata import download
15 from allmydata.uri import from_string_verifier, CHKFileVerifierURI
16 from allmydata.upload import FileHandle, FileName
17 from allmydata import provisioning
18 from allmydata import get_package_versions_string
19 from zope.interface import implements, Interface
20 import urllib
21 from formless import webform
22 from foolscap.eventual import fireEventually
23
24 from nevow.util import resource_filename
25
26 from allmydata.web import status, unlinked, introweb
27 from allmydata.web.common import IClient, getxmlfile, get_arg, \
28      boolean_of_arg, abbreviate_size
29
30 class ILocalAccess(Interface):
31     def local_access_is_allowed():
32         """Return True if t=upload&localdir= is allowed, giving anyone who
33         can talk to the webserver control over the local (disk) filesystem."""
34
35 # we must override twisted.web.http.Request.requestReceived with a version
36 # that doesn't use cgi.parse_multipart() . Since we actually use Nevow, we
37 # override the nevow-specific subclass, nevow.appserver.NevowRequest . This
38 # is an exact copy of twisted.web.http.Request (from SVN HEAD on 10-Aug-2007)
39 # that modifies the way form arguments are parsed. Note that this sort of
40 # surgery may induce a dependency upon a particular version of twisted.web
41
42 parse_qs = http.parse_qs
43 class MyRequest(appserver.NevowRequest):
44     fields = None
45     def requestReceived(self, command, path, version):
46         """Called by channel when all data has been received.
47
48         This method is not intended for users.
49         """
50         self.content.seek(0,0)
51         self.args = {}
52         self.stack = []
53
54         self.method, self.uri = command, path
55         self.clientproto = version
56         x = self.uri.split('?', 1)
57
58         if len(x) == 1:
59             self.path = self.uri
60         else:
61             self.path, argstring = x
62             self.args = parse_qs(argstring, 1)
63
64         # cache the client and server information, we'll need this later to be
65         # serialized and sent with the request so CGIs will work remotely
66         self.client = self.channel.transport.getPeer()
67         self.host = self.channel.transport.getHost()
68
69         # Argument processing.
70
71 ##      The original twisted.web.http.Request.requestReceived code parsed the
72 ##      content and added the form fields it found there to self.args . It
73 ##      did this with cgi.parse_multipart, which holds the arguments in RAM
74 ##      and is thus unsuitable for large file uploads. The Nevow subclass
75 ##      (nevow.appserver.NevowRequest) uses cgi.FieldStorage instead (putting
76 ##      the results in self.fields), which is much more memory-efficient.
77 ##      Since we know we're using Nevow, we can anticipate these arguments
78 ##      appearing in self.fields instead of self.args, and thus skip the
79 ##      parse-content-into-self.args step.
80
81 ##      args = self.args
82 ##      ctype = self.getHeader('content-type')
83 ##      if self.method == "POST" and ctype:
84 ##          mfd = 'multipart/form-data'
85 ##          key, pdict = cgi.parse_header(ctype)
86 ##          if key == 'application/x-www-form-urlencoded':
87 ##              args.update(parse_qs(self.content.read(), 1))
88 ##          elif key == mfd:
89 ##              try:
90 ##                  args.update(cgi.parse_multipart(self.content, pdict))
91 ##              except KeyError, e:
92 ##                  if e.args[0] == 'content-disposition':
93 ##                      # Parse_multipart can't cope with missing
94 ##                      # content-dispostion headers in multipart/form-data
95 ##                      # parts, so we catch the exception and tell the client
96 ##                      # it was a bad request.
97 ##                      self.channel.transport.write(
98 ##                              "HTTP/1.1 400 Bad Request\r\n\r\n")
99 ##                      self.channel.transport.loseConnection()
100 ##                      return
101 ##                  raise
102
103         self.process()
104
105     def _logger(self):
106         # we build up a log string that hides most of the cap, to preserve
107         # user privacy. We retain the query args so we can identify things
108         # like t=json. Then we send it to the flog. We make no attempt to
109         # match apache formatting. TODO: when we move to DSA dirnodes and
110         # shorter caps, consider exposing a few characters of the cap, or
111         # maybe a few characters of its hash.
112         x = self.uri.split("?", 1)
113         if len(x) == 1:
114             # no query args
115             path = self.uri
116             queryargs = ""
117         else:
118             path, queryargs = x
119             # there is a form handler which redirects POST /uri?uri=FOO into
120             # GET /uri/FOO so folks can paste in non-HTTP-prefixed uris. Make
121             # sure we censor these too.
122             if queryargs.startswith("uri="):
123                 queryargs = "[uri=CENSORED]"
124             queryargs = "?" + queryargs
125         if path.startswith("/uri"):
126             path = "/uri/[CENSORED].."
127         uri = path + queryargs
128
129         log.msg(format="web: %(clientip)s %(method)s %(uri)s %(code)s %(length)s",
130                 clientip=self.getClientIP(),
131                 method=self.method,
132                 uri=uri,
133                 code=self.code,
134                 length=(self.sentLength or "-"),
135                 facility="tahoe.webish",
136                 level=log.OPERATIONAL,
137                 )
138
139 class Directory(rend.Page):
140     addSlash = True
141     docFactory = getxmlfile("directory.xhtml")
142
143     def __init__(self, rootname, dirnode, dirpath):
144         self._rootname = rootname
145         self._dirnode = dirnode
146         self._dirpath = dirpath
147
148     def dirpath_as_string(self):
149         return "/" + "/".join(self._dirpath)
150
151     def render_title(self, ctx, data):
152         return ctx.tag["Directory '%s':" % self.dirpath_as_string()]
153
154     def render_header(self, ctx, data):
155         parent_directories = ("<%s>" % self._rootname,) + self._dirpath
156         num_dirs = len(parent_directories)
157
158         header = ["Directory '"]
159         for i,d in enumerate(parent_directories):
160             upness = num_dirs - i - 1
161             if upness:
162                 link = "/".join( ("..",) * upness )
163             else:
164                 link = "."
165             header.append(T.a(href=link)[d])
166             if upness != 0:
167                 header.append("/")
168         header.append("'")
169
170         if self._dirnode.is_readonly():
171             header.append(" (readonly)")
172         header.append(":")
173         return ctx.tag[header]
174
175     def render_welcome(self, ctx, data):
176         depth = len(self._dirpath) + 2
177         link = "/".join([".."] * depth)
178         return T.div[T.a(href=link)["Return to Welcome page"]]
179
180     def data_children(self, ctx, data):
181         d = self._dirnode.list()
182         d.addCallback(lambda dict: sorted(dict.items()))
183         def _stall_some(items):
184             # Deferreds don't optimize out tail recursion, and the way
185             # Nevow's flattener handles Deferreds doesn't take this into
186             # account. As a result, large lists of Deferreds that fire in the
187             # same turn (i.e. the output of defer.succeed) will cause a stack
188             # overflow. To work around this, we insert a turn break after
189             # every 100 items, using foolscap's fireEventually(). This gives
190             # the stack a chance to be popped. It would also work to put
191             # every item in its own turn, but that'd be a lot more
192             # inefficient. This addresses ticket #237, for which I was never
193             # able to create a failing unit test.
194             output = []
195             for i,item in enumerate(items):
196                 if i % 100 == 0:
197                     output.append(fireEventually(item))
198                 else:
199                     output.append(item)
200             return output
201         d.addCallback(_stall_some)
202         return d
203
204     def render_row(self, ctx, data):
205         name, (target, metadata) = data
206         name = name.encode("utf-8")
207         assert not isinstance(name, unicode)
208
209         if self._dirnode.is_readonly():
210             delete = "-"
211             rename = "-"
212         else:
213             # this creates a button which will cause our child__delete method
214             # to be invoked, which deletes the file and then redirects the
215             # browser back to this directory
216             delete = T.form(action=url.here, method="post")[
217                 T.input(type='hidden', name='t', value='delete'),
218                 T.input(type='hidden', name='name', value=name),
219                 T.input(type='hidden', name='when_done', value=url.here),
220                 T.input(type='submit', value='del', name="del"),
221                 ]
222
223             rename = T.form(action=url.here, method="get")[
224                 T.input(type='hidden', name='t', value='rename-form'),
225                 T.input(type='hidden', name='name', value=name),
226                 T.input(type='hidden', name='when_done', value=url.here),
227                 T.input(type='submit', value='rename', name="rename"),
228                 ]
229
230         ctx.fillSlots("delete", delete)
231         ctx.fillSlots("rename", rename)
232         check = T.form(action=url.here, method="post")[
233             T.input(type='hidden', name='t', value='check'),
234             T.input(type='hidden', name='name', value=name),
235             T.input(type='hidden', name='when_done', value=url.here),
236             T.input(type='submit', value='check', name="check"),
237             ]
238         ctx.fillSlots("overwrite", self.build_overwrite(ctx, (name, target)))
239         ctx.fillSlots("check", check)
240
241         times = []
242         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
243         if "ctime" in metadata:
244             ctime = time.strftime(TIME_FORMAT,
245                                   time.localtime(metadata["ctime"]))
246             times.append("c: " + ctime)
247         if "mtime" in metadata:
248             mtime = time.strftime(TIME_FORMAT,
249                                   time.localtime(metadata["mtime"]))
250             if times:
251                 times.append(T.br())
252                 times.append("m: " + mtime)
253         ctx.fillSlots("times", times)
254
255
256         # build the base of the uri_link link url
257         uri_link = "/uri/" + urllib.quote(target.get_uri())
258
259         assert (IFileNode.providedBy(target)
260                 or IDirectoryNode.providedBy(target)
261                 or IMutableFileNode.providedBy(target)), target
262
263         if IMutableFileNode.providedBy(target):
264             # file
265
266             # add the filename to the uri_link url
267             uri_link += '?%s' % (urllib.urlencode({'filename': name}),)
268
269             # to prevent javascript in displayed .html files from stealing a
270             # secret directory URI from the URL, send the browser to a URI-based
271             # page that doesn't know about the directory at all
272             #dlurl = urllib.quote(name)
273             dlurl = uri_link
274
275             ctx.fillSlots("filename",
276                           T.a(href=dlurl)[html.escape(name)])
277             ctx.fillSlots("type", "SSK")
278
279             ctx.fillSlots("size", "?")
280
281             text_plain_link = uri_link + "?filename=foo.txt"
282             text_plain_tag = T.a(href=text_plain_link)["text/plain"]
283
284         elif IFileNode.providedBy(target):
285             # file
286
287             # add the filename to the uri_link url
288             uri_link += '?%s' % (urllib.urlencode({'filename': name}),)
289
290             # to prevent javascript in displayed .html files from stealing a
291             # secret directory URI from the URL, send the browser to a URI-based
292             # page that doesn't know about the directory at all
293             #dlurl = urllib.quote(name)
294             dlurl = uri_link
295
296             ctx.fillSlots("filename",
297                           T.a(href=dlurl)[html.escape(name)])
298             ctx.fillSlots("type", "FILE")
299
300             ctx.fillSlots("size", target.get_size())
301
302             text_plain_link = uri_link + "?filename=foo.txt"
303             text_plain_tag = T.a(href=text_plain_link)["text/plain"]
304
305         elif IDirectoryNode.providedBy(target):
306             # directory
307             ctx.fillSlots("filename",
308                           T.a(href=uri_link)[html.escape(name)])
309             if target.is_readonly():
310                 dirtype = "DIR-RO"
311             else:
312                 dirtype = "DIR"
313             ctx.fillSlots("type", dirtype)
314             ctx.fillSlots("size", "-")
315             text_plain_tag = None
316
317         childdata = [T.a(href="%s?t=json" % name)["JSON"], ", ",
318                      T.a(href="%s?t=uri" % name)["URI"], ", ",
319                      T.a(href="%s?t=readonly-uri" % name)["readonly-URI"],
320                      ]
321         if text_plain_tag:
322             childdata.extend([", ", text_plain_tag])
323
324         ctx.fillSlots("data", childdata)
325
326         try:
327             checker = IClient(ctx).getServiceNamed("checker")
328         except KeyError:
329             checker = None
330         if checker:
331             d = defer.maybeDeferred(checker.checker_results_for,
332                                     target.get_verifier())
333             def _got(checker_results):
334                 recent_results = reversed(checker_results[-5:])
335                 if IFileNode.providedBy(target):
336                     results = ("[" +
337                                ", ".join(["%d/%d" % (found, needed)
338                                           for (when,
339                                                (needed, total, found, sharemap))
340                                           in recent_results]) +
341                                "]")
342                 elif IDirectoryNode.providedBy(target):
343                     results = ("[" +
344                                "".join([{True:"+",False:"-"}[res]
345                                         for (when, res) in recent_results]) +
346                                "]")
347                 else:
348                     results = "%d results" % len(checker_results)
349                 return results
350             d.addCallback(_got)
351             results = d
352         else:
353             results = "--"
354         # TODO: include a link to see more results, including timestamps
355         # TODO: use a sparkline
356         ctx.fillSlots("checker_results", results)
357
358         return ctx.tag
359
360     def render_forms(self, ctx, data):
361         if self._dirnode.is_readonly():
362             return T.div["No upload forms: directory is read-only"]
363         mkdir = T.form(action=".", method="post",
364                        enctype="multipart/form-data")[
365             T.fieldset[
366             T.input(type="hidden", name="t", value="mkdir"),
367             T.input(type="hidden", name="when_done", value=url.here),
368             T.legend(class_="freeform-form-label")["Create a new directory"],
369             "New directory name: ",
370             T.input(type="text", name="name"), " ",
371             T.input(type="submit", value="Create"),
372             ]]
373
374         upload = T.form(action=".", method="post",
375                         enctype="multipart/form-data")[
376             T.fieldset[
377             T.input(type="hidden", name="t", value="upload"),
378             T.input(type="hidden", name="when_done", value=url.here),
379             T.legend(class_="freeform-form-label")["Upload a file to this directory"],
380             "Choose a file to upload: ",
381             T.input(type="file", name="file", class_="freeform-input-file"),
382             " ",
383             T.input(type="submit", value="Upload"),
384             " Mutable?:",
385             T.input(type="checkbox", name="mutable"),
386             ]]
387
388         mount = T.form(action=".", method="post",
389                         enctype="multipart/form-data")[
390             T.fieldset[
391             T.input(type="hidden", name="t", value="uri"),
392             T.input(type="hidden", name="when_done", value=url.here),
393             T.legend(class_="freeform-form-label")["Attach a file or directory"
394                                                    " (by URI) to this"
395                                                    " directory"],
396             "New child name: ",
397             T.input(type="text", name="name"), " ",
398             "URI of new child: ",
399             T.input(type="text", name="uri"), " ",
400             T.input(type="submit", value="Attach"),
401             ]]
402         return [T.div(class_="freeform-form")[mkdir],
403                 T.div(class_="freeform-form")[upload],
404                 T.div(class_="freeform-form")[mount],
405                 ]
406
407     def build_overwrite(self, ctx, data):
408         name, target = data
409         if IMutableFileNode.providedBy(target) and not target.is_readonly():
410             action="/uri/" + urllib.quote(target.get_uri())
411             overwrite = T.form(action=action, method="post",
412                                enctype="multipart/form-data")[
413                 T.fieldset[
414                 T.input(type="hidden", name="t", value="overwrite"),
415                 T.input(type='hidden', name='name', value=name),
416                 T.input(type='hidden', name='when_done', value=url.here),
417                 T.legend(class_="freeform-form-label")["Overwrite"],
418                 "Choose new file: ",
419                 T.input(type="file", name="file", class_="freeform-input-file"),
420                 " ",
421                 T.input(type="submit", value="Overwrite")
422                 ]]
423             return [T.div(class_="freeform-form")[overwrite],]
424         else:
425             return []
426
427     def render_results(self, ctx, data):
428         req = inevow.IRequest(ctx)
429         return get_arg(req, "results", "")
430
431 class WebDownloadTarget:
432     implements(IDownloadTarget, IConsumer)
433     def __init__(self, req, content_type, content_encoding, save_to_file):
434         self._req = req
435         self._content_type = content_type
436         self._content_encoding = content_encoding
437         self._opened = False
438         self._producer = None
439         self._save_to_file = save_to_file
440
441     def registerProducer(self, producer, streaming):
442         self._req.registerProducer(producer, streaming)
443     def unregisterProducer(self):
444         self._req.unregisterProducer()
445
446     def open(self, size):
447         self._opened = True
448         self._req.setHeader("content-type", self._content_type)
449         if self._content_encoding:
450             self._req.setHeader("content-encoding", self._content_encoding)
451         self._req.setHeader("content-length", str(size))
452         if self._save_to_file is not None:
453             # tell the browser to save the file rather display it
454             # TODO: quote save_to_file properly
455             filename = self._save_to_file.encode("utf-8")
456             self._req.setHeader("content-disposition",
457                                 'attachment; filename="%s"'
458                                 % filename)
459
460     def write(self, data):
461         self._req.write(data)
462     def close(self):
463         self._req.finish()
464
465     def fail(self, why):
466         if self._opened:
467             # The content-type is already set, and the response code
468             # has already been sent, so we can't provide a clean error
469             # indication. We can emit text (which a browser might interpret
470             # as something else), and if we sent a Size header, they might
471             # notice that we've truncated the data. Keep the error message
472             # small to improve the chances of having our error response be
473             # shorter than the intended results.
474             #
475             # We don't have a lot of options, unfortunately.
476             self._req.write("problem during download\n")
477         else:
478             # We haven't written anything yet, so we can provide a sensible
479             # error message.
480             msg = str(why.type)
481             msg.replace("\n", "|")
482             self._req.setResponseCode(http.GONE, msg)
483             self._req.setHeader("content-type", "text/plain")
484             # TODO: HTML-formatted exception?
485             self._req.write(str(why))
486         self._req.finish()
487
488     def register_canceller(self, cb):
489         pass
490     def finish(self):
491         pass
492
493 class FileDownloader(resource.Resource):
494     def __init__(self, filenode, name):
495         assert (IFileNode.providedBy(filenode)
496                 or IMutableFileNode.providedBy(filenode))
497         self._filenode = filenode
498         self._name = name
499
500     def render(self, req):
501         gte = static.getTypeAndEncoding
502         ctype, encoding = gte(self._name,
503                               static.File.contentTypes,
504                               static.File.contentEncodings,
505                               defaultType="text/plain")
506         save_to_file = None
507         if get_arg(req, "save", False):
508             # TODO: make the API specification clear: should "save=" or
509             # "save=false" count?
510             save_to_file = self._name
511         wdt = WebDownloadTarget(req, ctype, encoding, save_to_file)
512         d = self._filenode.download(wdt)
513         # exceptions during download are handled by the WebDownloadTarget
514         d.addErrback(lambda why: None)
515         return server.NOT_DONE_YET
516
517 class BlockingFileError(Exception):
518     """We cannot auto-create a parent directory, because there is a file in
519     the way"""
520 class NoReplacementError(Exception):
521     """There was already a child by that name, and you asked me to not replace it"""
522 class NoLocalDirectoryError(Exception):
523     """The localdir= directory didn't exist"""
524
525 LOCALHOST = "127.0.0.1"
526
527 class NeedLocalhostError:
528     implements(inevow.IResource)
529
530     def renderHTTP(self, ctx):
531         req = inevow.IRequest(ctx)
532         req.setResponseCode(http.FORBIDDEN)
533         req.setHeader("content-type", "text/plain")
534         return "localfile= or localdir= requires a local connection"
535
536 class NeedAbsolutePathError:
537     implements(inevow.IResource)
538
539     def renderHTTP(self, ctx):
540         req = inevow.IRequest(ctx)
541         req.setResponseCode(http.FORBIDDEN)
542         req.setHeader("content-type", "text/plain")
543         return "localfile= or localdir= requires an absolute path"
544
545 class LocalAccessDisabledError:
546     implements(inevow.IResource)
547
548     def renderHTTP(self, ctx):
549         req = inevow.IRequest(ctx)
550         req.setResponseCode(http.FORBIDDEN)
551         req.setHeader("content-type", "text/plain")
552         return "local file access is disabled"
553
554 class WebError:
555     implements(inevow.IResource)
556     def __init__(self, response_code, errmsg):
557         self._response_code = response_code
558         self._errmsg = errmsg
559
560     def renderHTTP(self, ctx):
561         req = inevow.IRequest(ctx)
562         req.setResponseCode(self._response_code)
563         req.setHeader("content-type", "text/plain")
564         return self._errmsg
565
566
567 class LocalFileDownloader(resource.Resource):
568     def __init__(self, filenode, local_filename):
569         self._local_filename = local_filename
570         IFileNode(filenode)
571         self._filenode = filenode
572
573     def render(self, req):
574         target = download.FileName(self._local_filename)
575         d = self._filenode.download(target)
576         def _done(res):
577             req.write(self._filenode.get_uri())
578             req.finish()
579         d.addCallback(_done)
580         return server.NOT_DONE_YET
581
582
583 class FileJSONMetadata(rend.Page):
584     def __init__(self, filenode):
585         self._filenode = filenode
586
587     def renderHTTP(self, ctx):
588         req = inevow.IRequest(ctx)
589         req.setHeader("content-type", "text/plain")
590         return self.renderNode(self._filenode)
591
592     def renderNode(self, filenode):
593         file_uri = filenode.get_uri()
594         data = ("filenode",
595                 {'ro_uri': file_uri,
596                  'size': filenode.get_size(),
597                  })
598         return simplejson.dumps(data, indent=1)
599
600 class FileURI(FileJSONMetadata):
601     def renderNode(self, filenode):
602         file_uri = filenode.get_uri()
603         return file_uri
604
605 class FileReadOnlyURI(FileJSONMetadata):
606     def renderNode(self, filenode):
607         if filenode.is_readonly():
608             return filenode.get_uri()
609         else:
610             return filenode.get_readonly().get_uri()
611
612 class DirnodeWalkerMixin:
613     """Visit all nodes underneath (and including) the rootnode, one at a
614     time. For each one, call the visitor. The visitor will see the
615     IDirectoryNode before it sees any of the IFileNodes inside. If the
616     visitor returns a Deferred, I do not call the visitor again until it has
617     fired.
618     """
619
620 ##    def _walk_if_we_could_use_generators(self, rootnode, rootpath=()):
621 ##        # this is what we'd be doing if we didn't have the Deferreds and
622 ##        # thus could use generators
623 ##        yield rootpath, rootnode
624 ##        for childname, childnode in rootnode.list().items():
625 ##            childpath = rootpath + (childname,)
626 ##            if IFileNode.providedBy(childnode):
627 ##                yield childpath, childnode
628 ##            elif IDirectoryNode.providedBy(childnode):
629 ##                for res in self._walk_if_we_could_use_generators(childnode,
630 ##                                                                 childpath):
631 ##                    yield res
632
633     def walk(self, rootnode, visitor, rootpath=()):
634         d = rootnode.list()
635         def _listed(listing):
636             return listing.items()
637         d.addCallback(_listed)
638         d.addCallback(self._handle_items, visitor, rootpath)
639         return d
640
641     def _handle_items(self, items, visitor, rootpath):
642         if not items:
643             return
644         childname, (childnode, metadata) = items[0]
645         childpath = rootpath + (childname,)
646         d = defer.maybeDeferred(visitor, childpath, childnode, metadata)
647         if IDirectoryNode.providedBy(childnode):
648             d.addCallback(lambda res: self.walk(childnode, visitor, childpath))
649         d.addCallback(lambda res:
650                       self._handle_items(items[1:], visitor, rootpath))
651         return d
652
653 class LocalDirectoryDownloader(resource.Resource, DirnodeWalkerMixin):
654     def __init__(self, dirnode, localdir):
655         self._dirnode = dirnode
656         self._localdir = localdir
657
658     def _handle(self, path, node, metadata):
659         path = tuple([p.encode("utf-8") for p in path])
660         localfile = os.path.join(self._localdir, os.sep.join(path))
661         if IDirectoryNode.providedBy(node):
662             fileutil.make_dirs(localfile)
663         elif IFileNode.providedBy(node):
664             target = download.FileName(localfile)
665             return node.download(target)
666
667     def render(self, req):
668         d = self.walk(self._dirnode, self._handle)
669         def _done(res):
670             req.setHeader("content-type", "text/plain")
671             return "operation complete"
672         d.addCallback(_done)
673         return d
674
675 class DirectoryJSONMetadata(rend.Page):
676     def __init__(self, dirnode):
677         self._dirnode = dirnode
678
679     def renderHTTP(self, ctx):
680         req = inevow.IRequest(ctx)
681         req.setHeader("content-type", "text/plain")
682         return self.renderNode(self._dirnode)
683
684     def renderNode(self, node):
685         d = node.list()
686         def _got(children):
687             kids = {}
688             for name, (childnode, metadata) in children.iteritems():
689                 if IFileNode.providedBy(childnode):
690                     kiduri = childnode.get_uri()
691                     kiddata = ("filenode",
692                                {'ro_uri': kiduri,
693                                 'size': childnode.get_size(),
694                                 'metadata': metadata,
695                                 })
696                 else:
697                     assert IDirectoryNode.providedBy(childnode), (childnode, children,)
698                     kiddata = ("dirnode",
699                                {'ro_uri': childnode.get_readonly_uri(),
700                                 'metadata': metadata,
701                                 })
702                     if not childnode.is_readonly():
703                         kiddata[1]['rw_uri'] = childnode.get_uri()
704                 kids[name] = kiddata
705             contents = { 'children': kids,
706                          'ro_uri': node.get_readonly_uri(),
707                          }
708             if not node.is_readonly():
709                 contents['rw_uri'] = node.get_uri()
710             data = ("dirnode", contents)
711             return simplejson.dumps(data, indent=1)
712         d.addCallback(_got)
713         return d
714
715 class DirectoryURI(DirectoryJSONMetadata):
716     def renderNode(self, node):
717         return node.get_uri()
718
719 class DirectoryReadonlyURI(DirectoryJSONMetadata):
720     def renderNode(self, node):
721         return node.get_readonly_uri()
722
723 class RenameForm(rend.Page):
724     addSlash = True
725     docFactory = getxmlfile("rename-form.xhtml")
726
727     def __init__(self, rootname, dirnode, dirpath):
728         self._rootname = rootname
729         self._dirnode = dirnode
730         self._dirpath = dirpath
731
732     def dirpath_as_string(self):
733         return "/" + "/".join(self._dirpath)
734
735     def render_title(self, ctx, data):
736         return ctx.tag["Directory '%s':" % self.dirpath_as_string()]
737
738     def render_header(self, ctx, data):
739         parent_directories = ("<%s>" % self._rootname,) + self._dirpath
740         num_dirs = len(parent_directories)
741
742         header = [ "Rename in directory '",
743                    "<%s>/" % self._rootname,
744                    "/".join(self._dirpath),
745                    "':", ]
746
747         if self._dirnode.is_readonly():
748             header.append(" (readonly)")
749         return ctx.tag[header]
750
751     def render_when_done(self, ctx, data):
752         return T.input(type="hidden", name="when_done", value=url.here)
753
754     def render_get_name(self, ctx, data):
755         req = inevow.IRequest(ctx)
756         name = get_arg(req, "name", "")
757         ctx.tag.attributes['value'] = name
758         return ctx.tag
759
760 class POSTHandler(rend.Page):
761     def __init__(self, node, replace):
762         self._node = node
763         self._replace = replace
764
765     def _check_replacement(self, name):
766         if self._replace:
767             return defer.succeed(None)
768         d = self._node.has_child(name)
769         def _got(present):
770             if present:
771                 raise NoReplacementError("There was already a child by that "
772                                          "name, and you asked me to not "
773                                          "replace it.")
774             return None
775         d.addCallback(_got)
776         return d
777
778     def _POST_mkdir(self, name):
779         d = self._check_replacement(name)
780         d.addCallback(lambda res: self._node.create_empty_directory(name))
781         d.addCallback(lambda res: "directory created")
782         return d
783
784     def _POST_mkdir_p(self, path):
785         path_ = tuple([seg.decode("utf-8") for seg in path.split('/') if seg ])
786         d = self._get_or_create_directories(self._node, path_)
787         d.addCallback(lambda node: node.get_uri())
788         return d
789
790     # this code stolen from PUTHandler: should be refactored to a more
791     # generally accesible place, perhaps...
792     def _get_or_create_directories(self, node, path):
793         if not IDirectoryNode.providedBy(node):
794             # unfortunately it is too late to provide the name of the
795             # blocking directory in the error message.
796             raise BlockingFileError("cannot create directory because there "
797                                     "is a file in the way")
798         if not path:
799             return defer.succeed(node)
800         d = node.get(path[0])
801         def _maybe_create(f):
802             f.trap(KeyError)
803             return node.create_empty_directory(path[0])
804         d.addErrback(_maybe_create)
805         d.addCallback(self._get_or_create_directories, path[1:])
806         return d
807
808     def _POST_uri(self, name, newuri):
809         d = self._check_replacement(name)
810         d.addCallback(lambda res: self._node.set_uri(name, newuri))
811         d.addCallback(lambda res: newuri)
812         return d
813
814     def _POST_delete(self, name):
815         if name is None:
816             # apparently an <input type="hidden" name="name" value="">
817             # won't show up in the resulting encoded form.. the 'name'
818             # field is completely missing. So to allow deletion of an
819             # empty file, we have to pretend that None means ''. The only
820             # downide of this is a slightly confusing error message if
821             # someone does a POST without a name= field. For our own HTML
822             # thisn't a big deal, because we create the 'delete' POST
823             # buttons ourselves.
824             name = ''
825         d = self._node.delete(name)
826         d.addCallback(lambda res: "thing deleted")
827         return d
828
829     def _POST_rename(self, name, from_name, to_name):
830         d = self._check_replacement(to_name)
831         d.addCallback(lambda res: self._node.get(from_name))
832         def add_dest(child):
833             uri = child.get_uri()
834             # now actually do the rename
835             return self._node.set_uri(to_name, uri)
836         d.addCallback(add_dest)
837         def rm_src(junk):
838             return self._node.delete(from_name)
839         d.addCallback(rm_src)
840         d.addCallback(lambda res: "thing renamed")
841         return d
842
843     def _POST_upload(self, contents, name, mutable, client):
844         if mutable:
845             # SDMF: files are small, and we can only upload data.
846             contents.file.seek(0)
847             data = contents.file.read()
848             #uploadable = FileHandle(contents.file)
849             d = self._check_replacement(name)
850             d.addCallback(lambda res: self._node.has_child(name))
851             def _checked(present):
852                 if present:
853                     # modify the existing one instead of creating a new
854                     # one
855                     d2 = self._node.get(name)
856                     def _got_newnode(newnode):
857                         d3 = newnode.overwrite(data)
858                         d3.addCallback(lambda res: newnode.get_uri())
859                         return d3
860                     d2.addCallback(_got_newnode)
861                 else:
862                     d2 = client.create_mutable_file(data)
863                     def _uploaded(newnode):
864                         d1 = self._node.set_node(name, newnode)
865                         d1.addCallback(lambda res: newnode.get_uri())
866                         return d1
867                     d2.addCallback(_uploaded)
868                 return d2
869             d.addCallback(_checked)
870         else:
871             uploadable = FileHandle(contents.file, convergence=client.convergence)
872             d = self._check_replacement(name)
873             d.addCallback(lambda res: self._node.add_file(name, uploadable))
874             def _done(newnode):
875                 return newnode.get_uri()
876             d.addCallback(_done)
877         return d
878
879     def _POST_overwrite(self, contents):
880         # SDMF: files are small, and we can only upload data.
881         contents.file.seek(0)
882         data = contents.file.read()
883         # TODO: 'name' handling needs review
884         d = defer.succeed(self._node)
885         def _got_child_overwrite(child_node):
886             child_node.overwrite(data)
887             return child_node.get_uri()
888         d.addCallback(_got_child_overwrite)
889         return d
890
891     def _POST_check(self, name):
892         d = self._node.get(name)
893         def _got_child_check(child_node):
894             d2 = child_node.check()
895             def _done(res):
896                 log.msg("checked %s, results %s" % (child_node, res),
897                         facility="tahoe.webish", level=log.NOISY)
898                 return str(res)
899             d2.addCallback(_done)
900             return d2
901         d.addCallback(_got_child_check)
902         return d
903
904     def _POST_set_children(self, children):
905         cs = []
906         for name, (file_or_dir, mddict) in children.iteritems():
907             cap = str(mddict.get('rw_uri') or mddict.get('ro_uri'))
908             cs.append((name, cap, mddict.get('metadata')))
909
910         d = self._node.set_children(cs)
911         d.addCallback(lambda res: "Okay so I did it.")
912         return d
913
914     def renderHTTP(self, ctx):
915         req = inevow.IRequest(ctx)
916
917         t = get_arg(req, "t")
918         assert t is not None
919
920         charset = get_arg(req, "_charset", "utf-8")
921
922         name = get_arg(req, "name", None)
923         if name and "/" in name:
924             req.setResponseCode(http.BAD_REQUEST)
925             req.setHeader("content-type", "text/plain")
926             return "name= may not contain a slash"
927         if name is not None:
928             name = name.strip()
929             name = name.decode(charset)
930             assert isinstance(name, unicode)
931         # we allow the user to delete an empty-named file, but not to create
932         # them, since that's an easy and confusing mistake to make
933
934         when_done = get_arg(req, "when_done", None)
935         if not boolean_of_arg(get_arg(req, "replace", "true")):
936             self._replace = False
937
938         if t == "mkdir":
939             if not name:
940                 raise RuntimeError("mkdir requires a name")
941             d = self._POST_mkdir(name)
942         elif t == "mkdir-p":
943             path = get_arg(req, "path")
944             if not path:
945                 raise RuntimeError("mkdir-p requires a path")
946             d = self._POST_mkdir_p(path)
947         elif t == "uri":
948             if not name:
949                 raise RuntimeError("set-uri requires a name")
950             newuri = get_arg(req, "uri")
951             assert newuri is not None
952             d = self._POST_uri(name, newuri)
953         elif t == "delete":
954             d = self._POST_delete(name)
955         elif t == "rename":
956             from_name = get_arg(req, "from_name")
957             if from_name is not None:
958                 from_name = from_name.strip()
959                 from_name = from_name.decode(charset)
960                 assert isinstance(from_name, unicode)
961             to_name = get_arg(req, "to_name")
962             if to_name is not None:
963                 to_name = to_name.strip()
964                 to_name = to_name.decode(charset)
965                 assert isinstance(to_name, unicode)
966             if not from_name or not to_name:
967                 raise RuntimeError("rename requires from_name and to_name")
968             if not IDirectoryNode.providedBy(self._node):
969                 raise RuntimeError("rename must only be called on directories")
970             for k,v in [ ('from_name', from_name), ('to_name', to_name) ]:
971                 if v and "/" in v:
972                     req.setResponseCode(http.BAD_REQUEST)
973                     req.setHeader("content-type", "text/plain")
974                     return "%s= may not contain a slash" % (k,)
975             d = self._POST_rename(name, from_name, to_name)
976         elif t == "upload":
977             contents = req.fields["file"]
978             name = name or contents.filename
979             if name is not None:
980                 name = name.strip()
981             if not name:
982                 # this prohibts empty, missing, and all-whitespace filenames
983                 raise RuntimeError("upload requires a name")
984             name = name.decode(charset)
985             assert isinstance(name, unicode)
986             mutable = boolean_of_arg(get_arg(req, "mutable", "false"))
987             d = self._POST_upload(contents, name, mutable, IClient(ctx))
988         elif t == "overwrite":
989             contents = req.fields["file"]
990             d = self._POST_overwrite(contents)
991         elif t == "check":
992             d = self._POST_check(name)
993         elif t == "set_children":
994             req.content.seek(0)
995             body = req.content.read()
996             try:
997                 children = simplejson.loads(body)
998             except ValueError, le:
999                 le.args = tuple(le.args + (body,))
1000                 # TODO test handling of bad JSON
1001                 raise
1002             d = self._POST_set_children(children)
1003         else:
1004             print "BAD t=%s" % t
1005             return "BAD t=%s" % t
1006         if when_done:
1007             d.addCallback(lambda res: url.URL.fromString(when_done))
1008         def _check_replacement(f):
1009             # TODO: make this more human-friendly: maybe send them to the
1010             # when_done page but with an extra query-arg that will display
1011             # the error message in a big box at the top of the page. The
1012             # directory page that when_done= usually points to accepts a
1013             # result= argument.. use that.
1014             f.trap(NoReplacementError)
1015             req.setResponseCode(http.CONFLICT)
1016             req.setHeader("content-type", "text/plain")
1017             return str(f.value)
1018         d.addErrback(_check_replacement)
1019         return d
1020
1021 class DELETEHandler(rend.Page):
1022     def __init__(self, node, name):
1023         self._node = node
1024         self._name = name
1025
1026     def renderHTTP(self, ctx):
1027         req = inevow.IRequest(ctx)
1028         d = self._node.delete(self._name)
1029         def _done(res):
1030             # what should this return??
1031             return "%s deleted" % self._name.encode("utf-8")
1032         d.addCallback(_done)
1033         def _trap_missing(f):
1034             f.trap(KeyError)
1035             req.setResponseCode(http.NOT_FOUND)
1036             req.setHeader("content-type", "text/plain")
1037             return "no such child %s" % self._name.encode("utf-8")
1038         d.addErrback(_trap_missing)
1039         return d
1040
1041 class PUTHandler(rend.Page):
1042     def __init__(self, node, path, t, localfile, localdir, replace):
1043         self._node = node
1044         self._path = path
1045         self._t = t
1046         self._localfile = localfile
1047         self._localdir = localdir
1048         self._replace = replace
1049
1050     def renderHTTP(self, ctx):
1051         client = IClient(ctx)
1052         req = inevow.IRequest(ctx)
1053         t = self._t
1054         localfile = self._localfile
1055         localdir = self._localdir
1056
1057         if t == "upload" and not (localfile or localdir):
1058             req.setResponseCode(http.BAD_REQUEST)
1059             req.setHeader("content-type", "text/plain")
1060             return "t=upload requires localfile= or localdir="
1061
1062         # we must traverse the path, creating new directories as necessary
1063         d = self._get_or_create_directories(self._node, self._path[:-1])
1064         name = self._path[-1]
1065         d.addCallback(self._check_replacement, name, self._replace)
1066         if t == "upload":
1067             if localfile:
1068                 d.addCallback(self._upload_localfile, localfile, name, convergence=client.convergence)
1069             else:
1070                 # localdir
1071                 # take the last step
1072                 d.addCallback(self._get_or_create_directories, self._path[-1:])
1073                 d.addCallback(self._upload_localdir, localdir, convergence=client.convergence)
1074         elif t == "uri":
1075             d.addCallback(self._attach_uri, req.content, name)
1076         elif t == "mkdir":
1077             d.addCallback(self._mkdir, name)
1078         else:
1079             d.addCallback(self._upload_file, req.content, name, convergence=client.convergence)
1080
1081         def _transform_error(f):
1082             errors = {BlockingFileError: http.BAD_REQUEST,
1083                       NoReplacementError: http.CONFLICT,
1084                       NoLocalDirectoryError: http.BAD_REQUEST,
1085                       }
1086             for k,v in errors.items():
1087                 if f.check(k):
1088                     req.setResponseCode(v)
1089                     req.setHeader("content-type", "text/plain")
1090                     return str(f.value)
1091             return f
1092         d.addErrback(_transform_error)
1093         return d
1094
1095     def _get_or_create_directories(self, node, path):
1096         if not IDirectoryNode.providedBy(node):
1097             # unfortunately it is too late to provide the name of the
1098             # blocking directory in the error message.
1099             raise BlockingFileError("cannot create directory because there "
1100                                     "is a file in the way")
1101         if not path:
1102             return defer.succeed(node)
1103         d = node.get(path[0])
1104         def _maybe_create(f):
1105             f.trap(KeyError)
1106             return node.create_empty_directory(path[0])
1107         d.addErrback(_maybe_create)
1108         d.addCallback(self._get_or_create_directories, path[1:])
1109         return d
1110
1111     def _check_replacement(self, node, name, replace):
1112         if replace:
1113             return node
1114         d = node.has_child(name)
1115         def _got(present):
1116             if present:
1117                 raise NoReplacementError("There was already a child by that "
1118                                          "name, and you asked me to not "
1119                                          "replace it.")
1120             return node
1121         d.addCallback(_got)
1122         return d
1123
1124     def _mkdir(self, node, name):
1125         d = node.create_empty_directory(name)
1126         def _done(newnode):
1127             return newnode.get_uri()
1128         d.addCallback(_done)
1129         return d
1130
1131     def _upload_file(self, node, contents, name, convergence):
1132         uploadable = FileHandle(contents, convergence=convergence)
1133         d = node.add_file(name, uploadable)
1134         def _done(filenode):
1135             log.msg("webish upload complete",
1136                     facility="tahoe.webish", level=log.NOISY)
1137             return filenode.get_uri()
1138         d.addCallback(_done)
1139         return d
1140
1141     def _upload_localfile(self, node, localfile, name, convergence):
1142         uploadable = FileName(localfile, convergence=convergence)
1143         d = node.add_file(name, uploadable)
1144         d.addCallback(lambda filenode: filenode.get_uri())
1145         return d
1146
1147     def _attach_uri(self, parentnode, contents, name):
1148         newuri = contents.read().strip()
1149         d = parentnode.set_uri(name, newuri)
1150         def _done(res):
1151             return newuri
1152         d.addCallback(_done)
1153         return d
1154
1155     def _upload_localdir(self, node, localdir, convergence):
1156         # build up a list of files to upload. TODO: for now, these files and
1157         # directories must have UTF-8 encoded filenames: anything else will
1158         # cause the upload to break.
1159         all_files = []
1160         all_dirs = []
1161         msg = "No files to upload! %s is empty" % localdir
1162         if not os.path.exists(localdir):
1163             msg = "%s doesn't exist!" % localdir
1164             raise NoLocalDirectoryError(msg)
1165         for root, dirs, files in os.walk(localdir):
1166             if root == localdir:
1167                 path = ()
1168             else:
1169                 relative_root = root[len(localdir)+1:]
1170                 path = tuple(relative_root.split(os.sep))
1171             for d in dirs:
1172                 this_dir = path + (d,)
1173                 this_dir = tuple([p.decode("utf-8") for p in this_dir])
1174                 all_dirs.append(this_dir)
1175             for f in files:
1176                 this_file = path + (f,)
1177                 this_file = tuple([p.decode("utf-8") for p in this_file])
1178                 all_files.append(this_file)
1179         d = defer.succeed(msg)
1180         for dir in all_dirs:
1181             if dir:
1182                 d.addCallback(self._makedir, node, dir)
1183         for f in all_files:
1184             d.addCallback(self._upload_one_file, node, localdir, f, convergence=convergence)
1185         return d
1186
1187     def _makedir(self, res, node, dir):
1188         d = defer.succeed(None)
1189         # get the parent. As long as os.walk gives us parents before
1190         # children, this ought to work
1191         d.addCallback(lambda res: node.get_child_at_path(dir[:-1]))
1192         # then create the child directory
1193         d.addCallback(lambda parent: parent.create_empty_directory(dir[-1]))
1194         return d
1195
1196     def _upload_one_file(self, res, node, localdir, f, convergence):
1197         # get the parent. We can be sure this exists because we already
1198         # went through and created all the directories we require.
1199         localfile = os.path.join(localdir, *f)
1200         d = node.get_child_at_path(f[:-1])
1201         d.addCallback(self._upload_localfile, localfile, f[-1], convergence=convergence)
1202         return d
1203
1204
1205 class Manifest(rend.Page):
1206     docFactory = getxmlfile("manifest.xhtml")
1207     def __init__(self, dirnode, dirpath):
1208         self._dirnode = dirnode
1209         self._dirpath = dirpath
1210
1211     def dirpath_as_string(self):
1212         return "/" + "/".join(self._dirpath)
1213
1214     def render_title(self, ctx):
1215         return T.title["Manifest of %s" % self.dirpath_as_string()]
1216
1217     def render_header(self, ctx):
1218         return T.p["Manifest of %s" % self.dirpath_as_string()]
1219
1220     def data_items(self, ctx, data):
1221         return self._dirnode.build_manifest()
1222
1223     def render_row(self, ctx, refresh_cap):
1224         ctx.fillSlots("refresh_capability", refresh_cap)
1225         return ctx.tag
1226
1227 class DeepSize(rend.Page):
1228
1229     def __init__(self, dirnode, dirpath):
1230         self._dirnode = dirnode
1231         self._dirpath = dirpath
1232
1233     def renderHTTP(self, ctx):
1234         inevow.IRequest(ctx).setHeader("content-type", "text/plain")
1235         d = self._dirnode.build_manifest()
1236         def _measure_size(manifest):
1237             total = 0
1238             for verifiercap in manifest:
1239                 u = from_string_verifier(verifiercap)
1240                 if isinstance(u, CHKFileVerifierURI):
1241                     total += u.size
1242             return str(total)
1243         d.addCallback(_measure_size)
1244         return d
1245
1246 class ChildError:
1247     implements(inevow.IResource)
1248     def renderHTTP(self, ctx):
1249         req = inevow.IRequest(ctx)
1250         req.setResponseCode(http.BAD_REQUEST)
1251         req.setHeader("content-type", "text/plain")
1252         return self.text
1253
1254 def child_error(text):
1255     ce = ChildError()
1256     ce.text = text
1257     return ce, ()
1258
1259 class VDrive(rend.Page):
1260
1261     def __init__(self, node, name):
1262         self.node = node
1263         self.name = name
1264
1265     def get_child_at_path(self, path):
1266         if path:
1267             return self.node.get_child_at_path(path)
1268         return defer.succeed(self.node)
1269
1270     def locateChild(self, ctx, segments):
1271         req = inevow.IRequest(ctx)
1272         method = req.method
1273         path = tuple([seg.decode("utf-8") for seg in segments])
1274
1275         t = get_arg(req, "t", "")
1276         localfile = get_arg(req, "localfile", None)
1277         if localfile is not None:
1278             if localfile != os.path.abspath(localfile):
1279                 return NeedAbsolutePathError(), ()
1280         localdir = get_arg(req, "localdir", None)
1281         if localdir is not None:
1282             if localdir != os.path.abspath(localdir):
1283                 return NeedAbsolutePathError(), ()
1284         if localfile or localdir:
1285             if not ILocalAccess(ctx).local_access_is_allowed():
1286                 return LocalAccessDisabledError(), ()
1287             if req.getHost().host != LOCALHOST:
1288                 return NeedLocalhostError(), ()
1289         # TODO: think about clobbering/revealing config files and node secrets
1290
1291         replace = boolean_of_arg(get_arg(req, "replace", "true"))
1292
1293         if method == "GET":
1294             # the node must exist, and our operation will be performed on the
1295             # node itself.
1296             d = self.get_child_at_path(path)
1297             def file_or_dir(node):
1298                 if (IFileNode.providedBy(node)
1299                     or IMutableFileNode.providedBy(node)):
1300                     filename = "unknown"
1301                     if path:
1302                         filename = path[-1]
1303                     filename = get_arg(req, "filename", filename)
1304                     if t == "download":
1305                         if localfile:
1306                             # write contents to a local file
1307                             return LocalFileDownloader(node, localfile), ()
1308                         # send contents as the result
1309                         return FileDownloader(node, filename), ()
1310                     elif t == "":
1311                         # send contents as the result
1312                         return FileDownloader(node, filename), ()
1313                     elif t == "json":
1314                         return FileJSONMetadata(node), ()
1315                     elif t == "uri":
1316                         return FileURI(node), ()
1317                     elif t == "readonly-uri":
1318                         return FileReadOnlyURI(node), ()
1319                     else:
1320                         return child_error("bad t=%s" % t)
1321                 elif IDirectoryNode.providedBy(node):
1322                     if t == "download":
1323                         if localdir:
1324                             # recursive download to a local directory
1325                             return LocalDirectoryDownloader(node, localdir), ()
1326                         return child_error("t=download requires localdir=")
1327                     elif t == "":
1328                         # send an HTML representation of the directory
1329                         return Directory(self.name, node, path), ()
1330                     elif t == "json":
1331                         return DirectoryJSONMetadata(node), ()
1332                     elif t == "uri":
1333                         return DirectoryURI(node), ()
1334                     elif t == "readonly-uri":
1335                         return DirectoryReadonlyURI(node), ()
1336                     elif t == "manifest":
1337                         return Manifest(node, path), ()
1338                     elif t == "deep-size":
1339                         return DeepSize(node, path), ()
1340                     elif t == 'rename-form':
1341                         return RenameForm(self.name, node, path), ()
1342                     else:
1343                         return child_error("bad t=%s" % t)
1344                 else:
1345                     return child_error("unknown node type")
1346             d.addCallback(file_or_dir)
1347         elif method == "POST":
1348             # the node must exist, and our operation will be performed on the
1349             # node itself.
1350             d = self.get_child_at_path(path)
1351             def _got_POST(node):
1352                 return POSTHandler(node, replace), ()
1353             d.addCallback(_got_POST)
1354         elif method == "DELETE":
1355             # the node must exist, and our operation will be performed on its
1356             # parent node.
1357             assert path # you can't delete the root
1358             d = self.get_child_at_path(path[:-1])
1359             def _got_DELETE(node):
1360                 return DELETEHandler(node, path[-1]), ()
1361             d.addCallback(_got_DELETE)
1362         elif method in ("PUT",):
1363             # the node may or may not exist, and our operation may involve
1364             # all the ancestors of the node.
1365             return PUTHandler(self.node, path, t, localfile, localdir, replace), ()
1366         else:
1367             return rend.NotFound
1368         return d
1369
1370 class Root(rend.Page):
1371
1372     addSlash = True
1373     docFactory = getxmlfile("welcome.xhtml")
1374
1375     def locateChild(self, ctx, segments):
1376         client = IClient(ctx)
1377         req = inevow.IRequest(ctx)
1378
1379         if not segments or segments[0] != "uri":
1380             return rend.Page.locateChild(self, ctx, segments)
1381
1382         segments = list(segments)
1383         while segments and not segments[-1]:
1384             segments.pop()
1385         if not segments:
1386             segments.append('')
1387         segments = tuple(segments)
1388
1389         if len(segments) == 1 or segments[1] == '':
1390             uri = get_arg(req, "uri", None)
1391             if uri is not None:
1392                 there = url.URL.fromContext(ctx)
1393                 there = there.clear("uri")
1394                 there = there.child("uri").child(uri)
1395                 return there, ()
1396
1397         if len(segments) == 1:
1398             # /uri
1399             if req.method == "PUT":
1400                 # either "PUT /uri" to create an unlinked file, or
1401                 # "PUT /uri?t=mkdir" to create an unlinked directory
1402                 t = get_arg(req, "t", "").strip()
1403                 if t == "":
1404                     mutable = bool(get_arg(req, "mutable", "").strip())
1405                     if mutable:
1406                         return unlinked.UnlinkedPUTSSKUploader(), ()
1407                     else:
1408                         return unlinked.UnlinkedPUTCHKUploader(), ()
1409                 if t == "mkdir":
1410                     return unlinked.UnlinkedPUTCreateDirectory(), ()
1411                 errmsg = "/uri only accepts PUT and PUT?t=mkdir"
1412                 return WebError(http.BAD_REQUEST, errmsg), ()
1413
1414             elif req.method == "POST":
1415                 # "POST /uri?t=upload&file=newfile" to upload an
1416                 # unlinked file or "POST /uri?t=mkdir" to create a
1417                 # new directory
1418                 t = get_arg(req, "t", "").strip()
1419                 if t in ("", "upload"):
1420                     mutable = bool(get_arg(req, "mutable", "").strip())
1421                     if mutable:
1422                         return unlinked.UnlinkedPOSTSSKUploader(), ()
1423                     else:
1424                         return unlinked.UnlinkedPOSTCHKUploader(client, req), ()
1425                 if t == "mkdir":
1426                     return unlinked.UnlinkedPOSTCreateDirectory(), ()
1427                 errmsg = "/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, and POST?t=mkdir"
1428                 return WebError(http.BAD_REQUEST, errmsg), ()
1429
1430         if len(segments) < 2:
1431             return rend.NotFound
1432
1433         uri = segments[1]
1434         d = defer.maybeDeferred(client.create_node_from_uri, uri)
1435         d.addCallback(lambda node: VDrive(node, uri))
1436         d.addCallback(lambda vd: vd.locateChild(ctx, segments[2:]))
1437         def _trap_KeyError(f):
1438             f.trap(KeyError)
1439             return rend.FourOhFour(), ()
1440         d.addErrback(_trap_KeyError)
1441         return d
1442
1443     child_webform_css = webform.defaultCSS
1444     child_tahoe_css = nevow_File(resource_filename('allmydata.web', 'tahoe.css'))
1445
1446     child_provisioning = provisioning.ProvisioningTool()
1447     child_status = status.Status()
1448
1449     def data_version(self, ctx, data):
1450         return get_package_versions_string()
1451     def data_import_path(self, ctx, data):
1452         return str(allmydata)
1453     def data_my_nodeid(self, ctx, data):
1454         return idlib.nodeid_b2a(IClient(ctx).nodeid)
1455     def data_storage(self, ctx, data):
1456         client = IClient(ctx)
1457         try:
1458             ss = client.getServiceNamed("storage")
1459         except KeyError:
1460             return "Not running"
1461         allocated = "about %s allocated" % abbreviate_size(ss.allocated_size())
1462         sizelimit = "no size limit"
1463         if ss.sizelimit is not None:
1464             sizelimit = "size limit is %s" % abbreviate_size(ss.sizelimit)
1465         return "%s, %s" % (allocated, sizelimit)
1466
1467     def data_introducer_furl(self, ctx, data):
1468         return IClient(ctx).introducer_furl
1469     def data_connected_to_introducer(self, ctx, data):
1470         if IClient(ctx).connected_to_introducer():
1471             return "yes"
1472         return "no"
1473
1474     def data_helper_furl(self, ctx, data):
1475         try:
1476             uploader = IClient(ctx).getServiceNamed("uploader")
1477         except KeyError:
1478             return None
1479         furl, connected = uploader.get_helper_info()
1480         return furl
1481     def data_connected_to_helper(self, ctx, data):
1482         try:
1483             uploader = IClient(ctx).getServiceNamed("uploader")
1484         except KeyError:
1485             return "no" # we don't even have an Uploader
1486         furl, connected = uploader.get_helper_info()
1487         if connected:
1488             return "yes"
1489         return "no"
1490
1491     def data_known_storage_servers(self, ctx, data):
1492         ic = IClient(ctx).introducer_client
1493         servers = [c
1494                    for c in ic.get_all_connectors().values()
1495                    if c.service_name == "storage"]
1496         return len(servers)
1497
1498     def data_connected_storage_servers(self, ctx, data):
1499         ic = IClient(ctx).introducer_client
1500         return len(ic.get_all_connections_for("storage"))
1501
1502     def data_services(self, ctx, data):
1503         ic = IClient(ctx).introducer_client
1504         c = [ (service_name, nodeid, rsc)
1505               for (nodeid, service_name), rsc
1506               in ic.get_all_connectors().items() ]
1507         c.sort()
1508         return c
1509
1510     def render_service_row(self, ctx, data):
1511         (service_name, nodeid, rsc) = data
1512         ctx.fillSlots("peerid", "%s %s" % (idlib.nodeid_b2a(nodeid),
1513                                            rsc.nickname))
1514         if rsc.rref:
1515             rhost = rsc.remote_host
1516             if nodeid == IClient(ctx).nodeid:
1517                 rhost_s = "(loopback)"
1518             elif isinstance(rhost, address.IPv4Address):
1519                 rhost_s = "%s:%d" % (rhost.host, rhost.port)
1520             else:
1521                 rhost_s = str(rhost)
1522             connected = "Yes: to " + rhost_s
1523             since = rsc.last_connect_time
1524         else:
1525             connected = "No"
1526             since = rsc.last_loss_time
1527
1528         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
1529         ctx.fillSlots("connected", connected)
1530         ctx.fillSlots("since", time.strftime(TIME_FORMAT, time.localtime(since)))
1531         ctx.fillSlots("announced", time.strftime(TIME_FORMAT,
1532                                                  time.localtime(rsc.announcement_time)))
1533         ctx.fillSlots("version", rsc.version)
1534         ctx.fillSlots("service_name", rsc.service_name)
1535
1536         return ctx.tag
1537
1538     def render_download_form(self, ctx, data):
1539         # this is a form where users can download files by URI
1540         form = T.form(action="uri", method="get",
1541                       enctype="multipart/form-data")[
1542             T.fieldset[
1543             T.legend(class_="freeform-form-label")["Download a file"],
1544             "URI to download: ",
1545             T.input(type="text", name="uri"), " ",
1546             "Filename to download as: ",
1547             T.input(type="text", name="filename"), " ",
1548             T.input(type="submit", value="Download!"),
1549             ]]
1550         return T.div[form]
1551
1552     def render_view_form(self, ctx, data):
1553         # this is a form where users can download files by URI, or jump to a
1554         # named directory
1555         form = T.form(action="uri", method="get",
1556                       enctype="multipart/form-data")[
1557             T.fieldset[
1558             T.legend(class_="freeform-form-label")["View a file or directory"],
1559             "URI to view: ",
1560             T.input(type="text", name="uri"), " ",
1561             T.input(type="submit", value="View!"),
1562             ]]
1563         return T.div[form]
1564
1565     def render_upload_form(self, ctx, data):
1566         # this is a form where users can upload unlinked files
1567         form = T.form(action="uri", method="post",
1568                       enctype="multipart/form-data")[
1569             T.fieldset[
1570             T.legend(class_="freeform-form-label")["Upload a file"],
1571             "Choose a file: ",
1572             T.input(type="file", name="file", class_="freeform-input-file"),
1573             T.input(type="hidden", name="t", value="upload"),
1574             " Mutable?:", T.input(type="checkbox", name="mutable"),
1575             T.input(type="submit", value="Upload!"),
1576             ]]
1577         return T.div[form]
1578
1579     def render_mkdir_form(self, ctx, data):
1580         # this is a form where users can create new directories
1581         form = T.form(action="uri", method="post",
1582                       enctype="multipart/form-data")[
1583             T.fieldset[
1584             T.legend(class_="freeform-form-label")["Create a directory"],
1585             T.input(type="hidden", name="t", value="mkdir"),
1586             T.input(type="hidden", name="redirect_to_result", value="true"),
1587             T.input(type="submit", value="Create Directory!"),
1588             ]]
1589         return T.div[form]
1590
1591
1592 class LocalAccess:
1593     implements(ILocalAccess)
1594     def __init__(self):
1595         self.local_access = False
1596     def local_access_is_allowed(self):
1597         return self.local_access
1598
1599 class WebishServer(service.MultiService):
1600     name = "webish"
1601     root_class = Root
1602
1603     def __init__(self, webport, nodeurl_path=None):
1604         service.MultiService.__init__(self)
1605         self.webport = webport
1606         self.root = self.root_class()
1607         self.site = site = appserver.NevowSite(self.root)
1608         self.site.requestFactory = MyRequest
1609         self.allow_local = LocalAccess()
1610         self.site.remember(self.allow_local, ILocalAccess)
1611         s = strports.service(webport, site)
1612         s.setServiceParent(self)
1613         self.listener = s # stash it so the tests can query for the portnum
1614         self._started = defer.Deferred()
1615         if nodeurl_path:
1616             self._started.addCallback(self._write_nodeurl_file, nodeurl_path)
1617
1618     def allow_local_access(self, enable=True):
1619         self.allow_local.local_access = enable
1620
1621     def startService(self):
1622         service.MultiService.startService(self)
1623         # to make various services available to render_* methods, we stash a
1624         # reference to the client on the NevowSite. This will be available by
1625         # adapting the 'context' argument to a special marker interface named
1626         # IClient.
1627         self.site.remember(self.parent, IClient)
1628         # I thought you could do the same with an existing interface, but
1629         # apparently 'ISite' does not exist
1630         #self.site._client = self.parent
1631         self._started.callback(None)
1632
1633     def _write_nodeurl_file(self, junk, nodeurl_path):
1634         # what is our webport?
1635         s = self.listener
1636         if isinstance(s, internet.TCPServer):
1637             base_url = "http://127.0.0.1:%d/" % s._port.getHost().port
1638         elif isinstance(s, internet.SSLServer):
1639             base_url = "https://127.0.0.1:%d/" % s._port.getHost().port
1640         else:
1641             base_url = None
1642         if base_url:
1643             f = open(nodeurl_path, 'wb')
1644             # this file is world-readable
1645             f.write(base_url + "\n")
1646             f.close()
1647
1648 class IntroducerWebishServer(WebishServer):
1649     root_class = introweb.IntroducerRoot