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