]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/webish.py
web: return a proper error upon POST with a bad t= value
[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             req.setResponseCode(http.BAD_REQUEST)
1005             req.setHeader("content-type", "text/plain")
1006             return "BAD t=%s" % t
1007         if when_done:
1008             d.addCallback(lambda res: url.URL.fromString(when_done))
1009         def _check_replacement(f):
1010             # TODO: make this more human-friendly: maybe send them to the
1011             # when_done page but with an extra query-arg that will display
1012             # the error message in a big box at the top of the page. The
1013             # directory page that when_done= usually points to accepts a
1014             # result= argument.. use that.
1015             f.trap(NoReplacementError)
1016             req.setResponseCode(http.CONFLICT)
1017             req.setHeader("content-type", "text/plain")
1018             return str(f.value)
1019         d.addErrback(_check_replacement)
1020         return d
1021
1022 class DELETEHandler(rend.Page):
1023     def __init__(self, node, name):
1024         self._node = node
1025         self._name = name
1026
1027     def renderHTTP(self, ctx):
1028         req = inevow.IRequest(ctx)
1029         d = self._node.delete(self._name)
1030         def _done(res):
1031             # what should this return??
1032             return "%s deleted" % self._name.encode("utf-8")
1033         d.addCallback(_done)
1034         def _trap_missing(f):
1035             f.trap(KeyError)
1036             req.setResponseCode(http.NOT_FOUND)
1037             req.setHeader("content-type", "text/plain")
1038             return "no such child %s" % self._name.encode("utf-8")
1039         d.addErrback(_trap_missing)
1040         return d
1041
1042 class PUTHandler(rend.Page):
1043     def __init__(self, node, path, t, localfile, localdir, replace):
1044         self._node = node
1045         self._path = path
1046         self._t = t
1047         self._localfile = localfile
1048         self._localdir = localdir
1049         self._replace = replace
1050
1051     def renderHTTP(self, ctx):
1052         client = IClient(ctx)
1053         req = inevow.IRequest(ctx)
1054         t = self._t
1055         localfile = self._localfile
1056         localdir = self._localdir
1057
1058         if t == "upload" and not (localfile or localdir):
1059             req.setResponseCode(http.BAD_REQUEST)
1060             req.setHeader("content-type", "text/plain")
1061             return "t=upload requires localfile= or localdir="
1062
1063         # we must traverse the path, creating new directories as necessary
1064         d = self._get_or_create_directories(self._node, self._path[:-1])
1065         name = self._path[-1]
1066         d.addCallback(self._check_replacement, name, self._replace)
1067         if t == "upload":
1068             if localfile:
1069                 d.addCallback(self._upload_localfile, localfile, name, convergence=client.convergence)
1070             else:
1071                 # localdir
1072                 # take the last step
1073                 d.addCallback(self._get_or_create_directories, self._path[-1:])
1074                 d.addCallback(self._upload_localdir, localdir, convergence=client.convergence)
1075         elif t == "uri":
1076             d.addCallback(self._attach_uri, req.content, name)
1077         elif t == "mkdir":
1078             d.addCallback(self._mkdir, name)
1079         else:
1080             d.addCallback(self._upload_file, req.content, name, convergence=client.convergence)
1081
1082         def _transform_error(f):
1083             errors = {BlockingFileError: http.BAD_REQUEST,
1084                       NoReplacementError: http.CONFLICT,
1085                       NoLocalDirectoryError: http.BAD_REQUEST,
1086                       }
1087             for k,v in errors.items():
1088                 if f.check(k):
1089                     req.setResponseCode(v)
1090                     req.setHeader("content-type", "text/plain")
1091                     return str(f.value)
1092             return f
1093         d.addErrback(_transform_error)
1094         return d
1095
1096     def _get_or_create_directories(self, node, path):
1097         if not IDirectoryNode.providedBy(node):
1098             # unfortunately it is too late to provide the name of the
1099             # blocking directory in the error message.
1100             raise BlockingFileError("cannot create directory because there "
1101                                     "is a file in the way")
1102         if not path:
1103             return defer.succeed(node)
1104         d = node.get(path[0])
1105         def _maybe_create(f):
1106             f.trap(KeyError)
1107             return node.create_empty_directory(path[0])
1108         d.addErrback(_maybe_create)
1109         d.addCallback(self._get_or_create_directories, path[1:])
1110         return d
1111
1112     def _check_replacement(self, node, name, replace):
1113         if replace:
1114             return node
1115         d = node.has_child(name)
1116         def _got(present):
1117             if present:
1118                 raise NoReplacementError("There was already a child by that "
1119                                          "name, and you asked me to not "
1120                                          "replace it.")
1121             return node
1122         d.addCallback(_got)
1123         return d
1124
1125     def _mkdir(self, node, name):
1126         d = node.create_empty_directory(name)
1127         def _done(newnode):
1128             return newnode.get_uri()
1129         d.addCallback(_done)
1130         return d
1131
1132     def _upload_file(self, node, contents, name, convergence):
1133         uploadable = FileHandle(contents, convergence=convergence)
1134         d = node.add_file(name, uploadable)
1135         def _done(filenode):
1136             log.msg("webish upload complete",
1137                     facility="tahoe.webish", level=log.NOISY)
1138             return filenode.get_uri()
1139         d.addCallback(_done)
1140         return d
1141
1142     def _upload_localfile(self, node, localfile, name, convergence):
1143         uploadable = FileName(localfile, convergence=convergence)
1144         d = node.add_file(name, uploadable)
1145         d.addCallback(lambda filenode: filenode.get_uri())
1146         return d
1147
1148     def _attach_uri(self, parentnode, contents, name):
1149         newuri = contents.read().strip()
1150         d = parentnode.set_uri(name, newuri)
1151         def _done(res):
1152             return newuri
1153         d.addCallback(_done)
1154         return d
1155
1156     def _upload_localdir(self, node, localdir, convergence):
1157         # build up a list of files to upload. TODO: for now, these files and
1158         # directories must have UTF-8 encoded filenames: anything else will
1159         # cause the upload to break.
1160         all_files = []
1161         all_dirs = []
1162         msg = "No files to upload! %s is empty" % localdir
1163         if not os.path.exists(localdir):
1164             msg = "%s doesn't exist!" % localdir
1165             raise NoLocalDirectoryError(msg)
1166         for root, dirs, files in os.walk(localdir):
1167             if root == localdir:
1168                 path = ()
1169             else:
1170                 relative_root = root[len(localdir)+1:]
1171                 path = tuple(relative_root.split(os.sep))
1172             for d in dirs:
1173                 this_dir = path + (d,)
1174                 this_dir = tuple([p.decode("utf-8") for p in this_dir])
1175                 all_dirs.append(this_dir)
1176             for f in files:
1177                 this_file = path + (f,)
1178                 this_file = tuple([p.decode("utf-8") for p in this_file])
1179                 all_files.append(this_file)
1180         d = defer.succeed(msg)
1181         for dir in all_dirs:
1182             if dir:
1183                 d.addCallback(self._makedir, node, dir)
1184         for f in all_files:
1185             d.addCallback(self._upload_one_file, node, localdir, f, convergence=convergence)
1186         return d
1187
1188     def _makedir(self, res, node, dir):
1189         d = defer.succeed(None)
1190         # get the parent. As long as os.walk gives us parents before
1191         # children, this ought to work
1192         d.addCallback(lambda res: node.get_child_at_path(dir[:-1]))
1193         # then create the child directory
1194         d.addCallback(lambda parent: parent.create_empty_directory(dir[-1]))
1195         return d
1196
1197     def _upload_one_file(self, res, node, localdir, f, convergence):
1198         # get the parent. We can be sure this exists because we already
1199         # went through and created all the directories we require.
1200         localfile = os.path.join(localdir, *f)
1201         d = node.get_child_at_path(f[:-1])
1202         d.addCallback(self._upload_localfile, localfile, f[-1], convergence=convergence)
1203         return d
1204
1205
1206 class Manifest(rend.Page):
1207     docFactory = getxmlfile("manifest.xhtml")
1208     def __init__(self, dirnode, dirpath):
1209         self._dirnode = dirnode
1210         self._dirpath = dirpath
1211
1212     def dirpath_as_string(self):
1213         return "/" + "/".join(self._dirpath)
1214
1215     def render_title(self, ctx):
1216         return T.title["Manifest of %s" % self.dirpath_as_string()]
1217
1218     def render_header(self, ctx):
1219         return T.p["Manifest of %s" % self.dirpath_as_string()]
1220
1221     def data_items(self, ctx, data):
1222         return self._dirnode.build_manifest()
1223
1224     def render_row(self, ctx, refresh_cap):
1225         ctx.fillSlots("refresh_capability", refresh_cap)
1226         return ctx.tag
1227
1228 class DeepSize(rend.Page):
1229
1230     def __init__(self, dirnode, dirpath):
1231         self._dirnode = dirnode
1232         self._dirpath = dirpath
1233
1234     def renderHTTP(self, ctx):
1235         inevow.IRequest(ctx).setHeader("content-type", "text/plain")
1236         d = self._dirnode.build_manifest()
1237         def _measure_size(manifest):
1238             total = 0
1239             for verifiercap in manifest:
1240                 u = from_string_verifier(verifiercap)
1241                 if isinstance(u, CHKFileVerifierURI):
1242                     total += u.size
1243             return str(total)
1244         d.addCallback(_measure_size)
1245         return d
1246
1247 class ChildError:
1248     implements(inevow.IResource)
1249     def renderHTTP(self, ctx):
1250         req = inevow.IRequest(ctx)
1251         req.setResponseCode(http.BAD_REQUEST)
1252         req.setHeader("content-type", "text/plain")
1253         return self.text
1254
1255 def child_error(text):
1256     ce = ChildError()
1257     ce.text = text
1258     return ce, ()
1259
1260 class VDrive(rend.Page):
1261
1262     def __init__(self, node, name):
1263         self.node = node
1264         self.name = name
1265
1266     def get_child_at_path(self, path):
1267         if path:
1268             return self.node.get_child_at_path(path)
1269         return defer.succeed(self.node)
1270
1271     def locateChild(self, ctx, segments):
1272         req = inevow.IRequest(ctx)
1273         method = req.method
1274         path = tuple([seg.decode("utf-8") for seg in segments])
1275
1276         t = get_arg(req, "t", "")
1277         localfile = get_arg(req, "localfile", None)
1278         if localfile is not None:
1279             if localfile != os.path.abspath(localfile):
1280                 return NeedAbsolutePathError(), ()
1281         localdir = get_arg(req, "localdir", None)
1282         if localdir is not None:
1283             if localdir != os.path.abspath(localdir):
1284                 return NeedAbsolutePathError(), ()
1285         if localfile or localdir:
1286             if not ILocalAccess(ctx).local_access_is_allowed():
1287                 return LocalAccessDisabledError(), ()
1288             if req.getHost().host != LOCALHOST:
1289                 return NeedLocalhostError(), ()
1290         # TODO: think about clobbering/revealing config files and node secrets
1291
1292         replace = boolean_of_arg(get_arg(req, "replace", "true"))
1293
1294         if method == "GET":
1295             # the node must exist, and our operation will be performed on the
1296             # node itself.
1297             d = self.get_child_at_path(path)
1298             def file_or_dir(node):
1299                 if (IFileNode.providedBy(node)
1300                     or IMutableFileNode.providedBy(node)):
1301                     filename = "unknown"
1302                     if path:
1303                         filename = path[-1]
1304                     filename = get_arg(req, "filename", filename)
1305                     if t == "download":
1306                         if localfile:
1307                             # write contents to a local file
1308                             return LocalFileDownloader(node, localfile), ()
1309                         # send contents as the result
1310                         return FileDownloader(node, filename), ()
1311                     elif t == "":
1312                         # send contents as the result
1313                         return FileDownloader(node, filename), ()
1314                     elif t == "json":
1315                         return FileJSONMetadata(node), ()
1316                     elif t == "uri":
1317                         return FileURI(node), ()
1318                     elif t == "readonly-uri":
1319                         return FileReadOnlyURI(node), ()
1320                     else:
1321                         return child_error("bad t=%s" % t)
1322                 elif IDirectoryNode.providedBy(node):
1323                     if t == "download":
1324                         if localdir:
1325                             # recursive download to a local directory
1326                             return LocalDirectoryDownloader(node, localdir), ()
1327                         return child_error("t=download requires localdir=")
1328                     elif t == "":
1329                         # send an HTML representation of the directory
1330                         return Directory(self.name, node, path), ()
1331                     elif t == "json":
1332                         return DirectoryJSONMetadata(node), ()
1333                     elif t == "uri":
1334                         return DirectoryURI(node), ()
1335                     elif t == "readonly-uri":
1336                         return DirectoryReadonlyURI(node), ()
1337                     elif t == "manifest":
1338                         return Manifest(node, path), ()
1339                     elif t == "deep-size":
1340                         return DeepSize(node, path), ()
1341                     elif t == 'rename-form':
1342                         return RenameForm(self.name, node, path), ()
1343                     else:
1344                         return child_error("bad t=%s" % t)
1345                 else:
1346                     return child_error("unknown node type")
1347             d.addCallback(file_or_dir)
1348         elif method == "POST":
1349             # the node must exist, and our operation will be performed on the
1350             # node itself.
1351             d = self.get_child_at_path(path)
1352             def _got_POST(node):
1353                 return POSTHandler(node, replace), ()
1354             d.addCallback(_got_POST)
1355         elif method == "DELETE":
1356             # the node must exist, and our operation will be performed on its
1357             # parent node.
1358             assert path # you can't delete the root
1359             d = self.get_child_at_path(path[:-1])
1360             def _got_DELETE(node):
1361                 return DELETEHandler(node, path[-1]), ()
1362             d.addCallback(_got_DELETE)
1363         elif method in ("PUT",):
1364             # the node may or may not exist, and our operation may involve
1365             # all the ancestors of the node.
1366             return PUTHandler(self.node, path, t, localfile, localdir, replace), ()
1367         else:
1368             return rend.NotFound
1369         return d
1370
1371 class Root(rend.Page):
1372
1373     addSlash = True
1374     docFactory = getxmlfile("welcome.xhtml")
1375
1376     def locateChild(self, ctx, segments):
1377         client = IClient(ctx)
1378         req = inevow.IRequest(ctx)
1379
1380         if not segments or segments[0] != "uri":
1381             return rend.Page.locateChild(self, ctx, segments)
1382
1383         segments = list(segments)
1384         while segments and not segments[-1]:
1385             segments.pop()
1386         if not segments:
1387             segments.append('')
1388         segments = tuple(segments)
1389
1390         if len(segments) == 1 or segments[1] == '':
1391             uri = get_arg(req, "uri", None)
1392             if uri is not None:
1393                 there = url.URL.fromContext(ctx)
1394                 there = there.clear("uri")
1395                 there = there.child("uri").child(uri)
1396                 return there, ()
1397
1398         if len(segments) == 1:
1399             # /uri
1400             if req.method == "PUT":
1401                 # either "PUT /uri" to create an unlinked file, or
1402                 # "PUT /uri?t=mkdir" to create an unlinked directory
1403                 t = get_arg(req, "t", "").strip()
1404                 if t == "":
1405                     mutable = bool(get_arg(req, "mutable", "").strip())
1406                     if mutable:
1407                         return unlinked.UnlinkedPUTSSKUploader(), ()
1408                     else:
1409                         return unlinked.UnlinkedPUTCHKUploader(), ()
1410                 if t == "mkdir":
1411                     return unlinked.UnlinkedPUTCreateDirectory(), ()
1412                 errmsg = "/uri only accepts PUT and PUT?t=mkdir"
1413                 return WebError(http.BAD_REQUEST, errmsg), ()
1414
1415             elif req.method == "POST":
1416                 # "POST /uri?t=upload&file=newfile" to upload an
1417                 # unlinked file or "POST /uri?t=mkdir" to create a
1418                 # new directory
1419                 t = get_arg(req, "t", "").strip()
1420                 if t in ("", "upload"):
1421                     mutable = bool(get_arg(req, "mutable", "").strip())
1422                     if mutable:
1423                         return unlinked.UnlinkedPOSTSSKUploader(), ()
1424                     else:
1425                         return unlinked.UnlinkedPOSTCHKUploader(client, req), ()
1426                 if t == "mkdir":
1427                     return unlinked.UnlinkedPOSTCreateDirectory(), ()
1428                 errmsg = "/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, and POST?t=mkdir"
1429                 return WebError(http.BAD_REQUEST, errmsg), ()
1430
1431         if len(segments) < 2:
1432             return rend.NotFound
1433
1434         uri = segments[1]
1435         d = defer.maybeDeferred(client.create_node_from_uri, uri)
1436         d.addCallback(lambda node: VDrive(node, uri))
1437         d.addCallback(lambda vd: vd.locateChild(ctx, segments[2:]))
1438         def _trap_KeyError(f):
1439             f.trap(KeyError)
1440             return rend.FourOhFour(), ()
1441         d.addErrback(_trap_KeyError)
1442         return d
1443
1444     child_webform_css = webform.defaultCSS
1445     child_tahoe_css = nevow_File(resource_filename('allmydata.web', 'tahoe.css'))
1446
1447     child_provisioning = provisioning.ProvisioningTool()
1448     child_status = status.Status()
1449     child_helper_status = status.HelperStatus()
1450     child_statistics = status.Statistics()
1451
1452     def data_version(self, ctx, data):
1453         return get_package_versions_string()
1454     def data_import_path(self, ctx, data):
1455         return str(allmydata)
1456     def data_my_nodeid(self, ctx, data):
1457         return idlib.nodeid_b2a(IClient(ctx).nodeid)
1458
1459     def render_services(self, ctx, data):
1460         ul = T.ul()
1461         client = IClient(ctx)
1462         try:
1463             ss = client.getServiceNamed("storage")
1464             allocated_s = abbreviate_size(ss.allocated_size())
1465             allocated = "about %s allocated" % allocated_s
1466             sizelimit = "no size limit"
1467             if ss.sizelimit is not None:
1468                 sizelimit = "size limit is %s" % abbreviate_size(ss.sizelimit)
1469             ul[T.li["Storage Server: %s, %s" % (allocated, sizelimit)]]
1470         except KeyError:
1471             ul[T.li["Not running storage server"]]
1472
1473         try:
1474             h = client.getServiceNamed("helper")
1475             stats = h.get_stats()
1476             active_uploads = stats["chk_upload_helper.active_uploads"]
1477             ul[T.li["Helper: %d active uploads" % (active_uploads,)]]
1478         except KeyError:
1479             ul[T.li["Not running helper"]]
1480
1481         return ctx.tag[ul]
1482
1483     def data_introducer_furl(self, ctx, data):
1484         return IClient(ctx).introducer_furl
1485     def data_connected_to_introducer(self, ctx, data):
1486         if IClient(ctx).connected_to_introducer():
1487             return "yes"
1488         return "no"
1489
1490     def data_helper_furl(self, ctx, data):
1491         try:
1492             uploader = IClient(ctx).getServiceNamed("uploader")
1493         except KeyError:
1494             return None
1495         furl, connected = uploader.get_helper_info()
1496         return furl
1497     def data_connected_to_helper(self, ctx, data):
1498         try:
1499             uploader = IClient(ctx).getServiceNamed("uploader")
1500         except KeyError:
1501             return "no" # we don't even have an Uploader
1502         furl, connected = uploader.get_helper_info()
1503         if connected:
1504             return "yes"
1505         return "no"
1506
1507     def data_known_storage_servers(self, ctx, data):
1508         ic = IClient(ctx).introducer_client
1509         servers = [c
1510                    for c in ic.get_all_connectors().values()
1511                    if c.service_name == "storage"]
1512         return len(servers)
1513
1514     def data_connected_storage_servers(self, ctx, data):
1515         ic = IClient(ctx).introducer_client
1516         return len(ic.get_all_connections_for("storage"))
1517
1518     def data_services(self, ctx, data):
1519         ic = IClient(ctx).introducer_client
1520         c = [ (service_name, nodeid, rsc)
1521               for (nodeid, service_name), rsc
1522               in ic.get_all_connectors().items() ]
1523         c.sort()
1524         return c
1525
1526     def render_service_row(self, ctx, data):
1527         (service_name, nodeid, rsc) = data
1528         ctx.fillSlots("peerid", "%s %s" % (idlib.nodeid_b2a(nodeid),
1529                                            rsc.nickname))
1530         if rsc.rref:
1531             rhost = rsc.remote_host
1532             if nodeid == IClient(ctx).nodeid:
1533                 rhost_s = "(loopback)"
1534             elif isinstance(rhost, address.IPv4Address):
1535                 rhost_s = "%s:%d" % (rhost.host, rhost.port)
1536             else:
1537                 rhost_s = str(rhost)
1538             connected = "Yes: to " + rhost_s
1539             since = rsc.last_connect_time
1540         else:
1541             connected = "No"
1542             since = rsc.last_loss_time
1543
1544         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
1545         ctx.fillSlots("connected", connected)
1546         ctx.fillSlots("since", time.strftime(TIME_FORMAT, time.localtime(since)))
1547         ctx.fillSlots("announced", time.strftime(TIME_FORMAT,
1548                                                  time.localtime(rsc.announcement_time)))
1549         ctx.fillSlots("version", rsc.version)
1550         ctx.fillSlots("service_name", rsc.service_name)
1551
1552         return ctx.tag
1553
1554     def render_download_form(self, ctx, data):
1555         # this is a form where users can download files by URI
1556         form = T.form(action="uri", method="get",
1557                       enctype="multipart/form-data")[
1558             T.fieldset[
1559             T.legend(class_="freeform-form-label")["Download a file"],
1560             "URI to download: ",
1561             T.input(type="text", name="uri"), " ",
1562             "Filename to download as: ",
1563             T.input(type="text", name="filename"), " ",
1564             T.input(type="submit", value="Download!"),
1565             ]]
1566         return T.div[form]
1567
1568     def render_view_form(self, ctx, data):
1569         # this is a form where users can download files by URI, or jump to a
1570         # named directory
1571         form = T.form(action="uri", method="get",
1572                       enctype="multipart/form-data")[
1573             T.fieldset[
1574             T.legend(class_="freeform-form-label")["View a file or directory"],
1575             "URI to view: ",
1576             T.input(type="text", name="uri"), " ",
1577             T.input(type="submit", value="View!"),
1578             ]]
1579         return T.div[form]
1580
1581     def render_upload_form(self, ctx, data):
1582         # this is a form where users can upload unlinked files
1583         form = T.form(action="uri", method="post",
1584                       enctype="multipart/form-data")[
1585             T.fieldset[
1586             T.legend(class_="freeform-form-label")["Upload a file"],
1587             "Choose a file: ",
1588             T.input(type="file", name="file", class_="freeform-input-file"),
1589             T.input(type="hidden", name="t", value="upload"),
1590             " Mutable?:", T.input(type="checkbox", name="mutable"),
1591             T.input(type="submit", value="Upload!"),
1592             ]]
1593         return T.div[form]
1594
1595     def render_mkdir_form(self, ctx, data):
1596         # this is a form where users can create new directories
1597         form = T.form(action="uri", method="post",
1598                       enctype="multipart/form-data")[
1599             T.fieldset[
1600             T.legend(class_="freeform-form-label")["Create a directory"],
1601             T.input(type="hidden", name="t", value="mkdir"),
1602             T.input(type="hidden", name="redirect_to_result", value="true"),
1603             T.input(type="submit", value="Create Directory!"),
1604             ]]
1605         return T.div[form]
1606
1607
1608 class LocalAccess:
1609     implements(ILocalAccess)
1610     def __init__(self):
1611         self.local_access = False
1612     def local_access_is_allowed(self):
1613         return self.local_access
1614
1615 class WebishServer(service.MultiService):
1616     name = "webish"
1617     root_class = Root
1618
1619     def __init__(self, webport, nodeurl_path=None):
1620         service.MultiService.__init__(self)
1621         self.webport = webport
1622         self.root = self.root_class()
1623         self.site = site = appserver.NevowSite(self.root)
1624         self.site.requestFactory = MyRequest
1625         self.allow_local = LocalAccess()
1626         self.site.remember(self.allow_local, ILocalAccess)
1627         s = strports.service(webport, site)
1628         s.setServiceParent(self)
1629         self.listener = s # stash it so the tests can query for the portnum
1630         self._started = defer.Deferred()
1631         if nodeurl_path:
1632             self._started.addCallback(self._write_nodeurl_file, nodeurl_path)
1633
1634     def allow_local_access(self, enable=True):
1635         self.allow_local.local_access = enable
1636
1637     def startService(self):
1638         service.MultiService.startService(self)
1639         # to make various services available to render_* methods, we stash a
1640         # reference to the client on the NevowSite. This will be available by
1641         # adapting the 'context' argument to a special marker interface named
1642         # IClient.
1643         self.site.remember(self.parent, IClient)
1644         # I thought you could do the same with an existing interface, but
1645         # apparently 'ISite' does not exist
1646         #self.site._client = self.parent
1647         self._started.callback(None)
1648
1649     def _write_nodeurl_file(self, junk, nodeurl_path):
1650         # what is our webport?
1651         s = self.listener
1652         if isinstance(s, internet.TCPServer):
1653             base_url = "http://127.0.0.1:%d/" % s._port.getHost().port
1654         elif isinstance(s, internet.SSLServer):
1655             base_url = "https://127.0.0.1:%d/" % s._port.getHost().port
1656         else:
1657             base_url = None
1658         if base_url:
1659             f = open(nodeurl_path, 'wb')
1660             # this file is world-readable
1661             f.write(base_url + "\n")
1662             f.close()
1663
1664 class IntroducerWebishServer(WebishServer):
1665     root_class = introweb.IntroducerRoot