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 text_plain(text, ctx):
86 req.setHeader("content-type", "text/plain")
87 req.setHeader("content-length", len(text))
90 class WebError(Exception):
91 def __init__(self, text, code=http.BAD_REQUEST):
95 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
96 # Internal Server Error, we either need to do that ICanHandleException trick,
97 # or make sure that childFactory returns a WebErrorResource (and never an
98 # actual exception). The latter is growing increasingly annoying.
100 def should_create_intermediate_directories(req):
101 t = get_arg(req, "t", "").strip()
102 return bool(req.method in ("PUT", "POST") and
103 t not in ("delete", "rename", "rename-form", "check"))
106 class MyExceptionHandler(appserver.DefaultExceptionHandler):
107 def simple(self, ctx, text, code=http.BAD_REQUEST):
109 req.setResponseCode(code)
110 req.setHeader("content-type", "text/plain;charset=utf-8")
111 if isinstance(text, unicode):
112 text = text.encode("utf-8")
114 # TODO: consider putting the requested URL here
115 req.finishRequest(False)
117 def renderHTTP_exception(self, ctx, f):
118 if f.check(ExistingChildError):
119 return self.simple(ctx,
120 "There was already a child by that "
121 "name, and you asked me to not "
124 elif f.check(NoSuchChildError):
125 name = f.value.args[0]
126 return self.simple(ctx,
127 "No such child: %s" % name.encode("utf-8"),
129 elif f.check(NotEnoughSharesError):
130 return self.simple(ctx, str(f), http.GONE)
131 elif f.check(WebError):
132 return self.simple(ctx, f.value.text, f.value.code)
133 elif f.check(FileTooLargeError):
134 return self.simple(ctx, str(f.value), http.REQUEST_ENTITY_TOO_LARGE)
135 elif f.check(server.UnsupportedMethod):
136 # twisted.web.server.Request.render() has support for transforming
137 # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
138 # return code, but nevow does not.
141 return self.simple(ctx,
142 "I don't know how to treat a %s request." % method,
143 http.NOT_IMPLEMENTED)
144 super = appserver.DefaultExceptionHandler
145 return super.renderHTTP_exception(self, ctx, f)
147 class NeedOperationHandleError(WebError):
152 def renderHTTP(self, ctx):
153 request = IRequest(ctx)
155 # if we were using regular twisted.web Resources (and the regular
156 # twisted.web.server.Request object) then we could implement
157 # render_PUT and render_GET. But Nevow's request handler
158 # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
159 # some code from the Resource.render method that Nevow bypasses, to
161 m = getattr(self, 'render_' + request.method, None)
163 from twisted.web.server import UnsupportedMethod
164 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))