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 IClient(Interface):
12 class IOpHandleTable(Interface):
16 return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
18 def boolean_of_arg(arg):
20 assert arg.lower() in ("true", "t", "1", "false", "f", "0", "on", "off")
21 return arg.lower() in ("true", "t", "1", "on")
23 def get_root(ctx_or_req):
24 req = IRequest(ctx_or_req)
25 # the addSlash=True gives us one extra (empty) segment
26 depth = len(req.prepath) + len(req.postpath) - 1
27 link = "/".join([".."] * depth)
30 def get_arg(ctx_or_req, argname, default=None, multiple=False):
31 """Extract an argument from either the query args (req.args) or the form
32 body fields (req.fields). If multiple=False, this returns a single value
33 (or the default, which defaults to None), and the query args take
34 precedence. If multiple=True, this returns a tuple of arguments (possibly
35 empty), starting with all those in the query args.
37 req = IRequest(ctx_or_req)
39 if argname in req.args:
40 results.extend(req.args[argname])
41 if req.fields and argname in req.fields:
42 results.append(req.fields[argname].value)
49 def abbreviate_time(data):
57 return "%dms" % (1000*s)
59 return "%.1fms" % (1000*s)
60 return "%dus" % (1000000*s)
62 def abbreviate_rate(data):
63 # 21.8kBps, 554.4kBps 4.37MBps
68 return "%1.2fMBps" % (r/1000000)
70 return "%.1fkBps" % (r/1000)
73 def abbreviate_size(data):
74 # 21.8kB, 554.4kB 4.37MB
79 return "%1.2fGB" % (r/1000000000)
81 return "%1.2fMB" % (r/1000000)
83 return "%.1fkB" % (r/1000)
86 def text_plain(text, ctx):
88 req.setHeader("content-type", "text/plain")
89 req.setHeader("content-length", len(text))
92 class WebError(Exception):
93 def __init__(self, text, code=http.BAD_REQUEST):
97 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
98 # Internal Server Error, we either need to do that ICanHandleException trick,
99 # or make sure that childFactory returns a WebErrorResource (and never an
100 # actual exception). The latter is growing increasingly annoying.
102 def should_create_intermediate_directories(req):
103 t = get_arg(req, "t", "").strip()
104 return bool(req.method in ("PUT", "POST") and
105 t not in ("delete", "rename", "rename-form", "check"))
108 class MyExceptionHandler(appserver.DefaultExceptionHandler):
109 def simple(self, ctx, text, code=http.BAD_REQUEST):
111 req.setResponseCode(code)
112 req.setHeader("content-type", "text/plain;charset=utf-8")
113 if isinstance(text, unicode):
114 text = text.encode("utf-8")
116 # TODO: consider putting the requested URL here
117 req.finishRequest(False)
119 def renderHTTP_exception(self, ctx, f):
120 if f.check(ExistingChildError):
121 return self.simple(ctx,
122 "There was already a child by that "
123 "name, and you asked me to not "
126 elif f.check(NoSuchChildError):
127 name = f.value.args[0]
128 return self.simple(ctx,
129 "No such child: %s" % name.encode("utf-8"),
131 elif f.check(NotEnoughSharesError):
132 return self.simple(ctx, str(f), http.GONE)
133 elif f.check(WebError):
134 return self.simple(ctx, f.value.text, f.value.code)
135 elif f.check(FileTooLargeError):
136 return self.simple(ctx, str(f.value), http.REQUEST_ENTITY_TOO_LARGE)
137 elif f.check(server.UnsupportedMethod):
138 # twisted.web.server.Request.render() has support for transforming
139 # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
140 # return code, but nevow does not.
143 return self.simple(ctx,
144 "I don't know how to treat a %s request." % method,
145 http.NOT_IMPLEMENTED)
146 super = appserver.DefaultExceptionHandler
147 return super.renderHTTP_exception(self, ctx, f)
149 class NeedOperationHandleError(WebError):
154 def renderHTTP(self, ctx):
155 request = IRequest(ctx)
157 # if we were using regular twisted.web Resources (and the regular
158 # twisted.web.server.Request object) then we could implement
159 # render_PUT and render_GET. But Nevow's request handler
160 # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
161 # some code from the Resource.render method that Nevow bypasses, to
163 m = getattr(self, 'render_' + request.method, None)
165 from twisted.web.server import UnsupportedMethod
166 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))