2 from twisted.web import http, server
3 from zope.interface import Interface
4 from nevow import loaders, appserver
5 from nevow.inevow import IRequest
6 from nevow.util import resource_filename
7 from allmydata.interfaces import ExistingChildError, NoSuchChildError, \
8 FileTooLargeError, NotEnoughSharesError
10 class IOpHandleTable(Interface):
14 return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
16 def boolean_of_arg(arg):
18 assert arg.lower() in ("true", "t", "1", "false", "f", "0", "on", "off")
19 return arg.lower() in ("true", "t", "1", "on")
21 def get_root(ctx_or_req):
22 req = IRequest(ctx_or_req)
23 # the addSlash=True gives us one extra (empty) segment
24 depth = len(req.prepath) + len(req.postpath) - 1
25 link = "/".join([".."] * depth)
28 def get_arg(ctx_or_req, argname, default=None, multiple=False):
29 """Extract an argument from either the query args (req.args) or the form
30 body fields (req.fields). If multiple=False, this returns a single value
31 (or the default, which defaults to None), and the query args take
32 precedence. If multiple=True, this returns a tuple of arguments (possibly
33 empty), starting with all those in the query args.
35 req = IRequest(ctx_or_req)
37 if argname in req.args:
38 results.extend(req.args[argname])
39 if req.fields and argname in req.fields:
40 results.append(req.fields[argname].value)
47 def abbreviate_time(data):
55 return "%dms" % (1000*s)
57 return "%.1fms" % (1000*s)
58 return "%dus" % (1000000*s)
60 def abbreviate_rate(data):
61 # 21.8kBps, 554.4kBps 4.37MBps
66 return "%1.2fMBps" % (r/1000000)
68 return "%.1fkBps" % (r/1000)
71 def abbreviate_size(data):
72 # 21.8kB, 554.4kB 4.37MB
77 return "%1.2fGB" % (r/1000000000)
79 return "%1.2fMB" % (r/1000000)
81 return "%.1fkB" % (r/1000)
84 def plural(sequence_or_length):
85 if isinstance(sequence_or_length, int):
86 length = sequence_or_length
88 length = len(sequence_or_length)
93 def text_plain(text, ctx):
95 req.setHeader("content-type", "text/plain")
96 req.setHeader("content-length", len(text))
99 class WebError(Exception):
100 def __init__(self, text, code=http.BAD_REQUEST):
104 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
105 # Internal Server Error, we either need to do that ICanHandleException trick,
106 # or make sure that childFactory returns a WebErrorResource (and never an
107 # actual exception). The latter is growing increasingly annoying.
109 def should_create_intermediate_directories(req):
110 t = get_arg(req, "t", "").strip()
111 return bool(req.method in ("PUT", "POST") and
112 t not in ("delete", "rename", "rename-form", "check"))
115 class MyExceptionHandler(appserver.DefaultExceptionHandler):
116 def simple(self, ctx, text, code=http.BAD_REQUEST):
118 req.setResponseCode(code)
119 req.setHeader("content-type", "text/plain;charset=utf-8")
120 if isinstance(text, unicode):
121 text = text.encode("utf-8")
123 # TODO: consider putting the requested URL here
124 req.finishRequest(False)
126 def renderHTTP_exception(self, ctx, f):
127 if f.check(ExistingChildError):
128 return self.simple(ctx,
129 "There was already a child by that "
130 "name, and you asked me to not "
133 elif f.check(NoSuchChildError):
134 name = f.value.args[0]
135 return self.simple(ctx,
136 "No such child: %s" % name.encode("utf-8"),
138 elif f.check(NotEnoughSharesError):
139 return self.simple(ctx, str(f), http.GONE)
140 elif f.check(WebError):
141 return self.simple(ctx, f.value.text, f.value.code)
142 elif f.check(FileTooLargeError):
143 return self.simple(ctx, str(f.value), http.REQUEST_ENTITY_TOO_LARGE)
144 elif f.check(server.UnsupportedMethod):
145 # twisted.web.server.Request.render() has support for transforming
146 # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
147 # return code, but nevow does not.
150 return self.simple(ctx,
151 "I don't know how to treat a %s request." % method,
152 http.NOT_IMPLEMENTED)
153 super = appserver.DefaultExceptionHandler
154 return super.renderHTTP_exception(self, ctx, f)
156 class NeedOperationHandleError(WebError):
161 def renderHTTP(self, ctx):
162 request = IRequest(ctx)
164 # if we were using regular twisted.web Resources (and the regular
165 # twisted.web.server.Request object) then we could implement
166 # render_PUT and render_GET. But Nevow's request handler
167 # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
168 # some code from the Resource.render method that Nevow bypasses, to
170 m = getattr(self, 'render_' + request.method, None)
172 from twisted.web.server import UnsupportedMethod
173 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))