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
9 from allmydata.util import abbreviate # TODO: consolidate
11 class IOpHandleTable(Interface):
15 return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
17 def boolean_of_arg(arg):
19 assert arg.lower() in ("true", "t", "1", "false", "f", "0", "on", "off")
20 return arg.lower() in ("true", "t", "1", "on")
22 def get_root(ctx_or_req):
23 req = IRequest(ctx_or_req)
24 # the addSlash=True gives us one extra (empty) segment
25 depth = len(req.prepath) + len(req.postpath) - 1
26 link = "/".join([".."] * depth)
29 def get_arg(ctx_or_req, argname, default=None, multiple=False):
30 """Extract an argument from either the query args (req.args) or the form
31 body fields (req.fields). If multiple=False, this returns a single value
32 (or the default, which defaults to None), and the query args take
33 precedence. If multiple=True, this returns a tuple of arguments (possibly
34 empty), starting with all those in the query args.
36 req = IRequest(ctx_or_req)
38 if argname in req.args:
39 results.extend(req.args[argname])
40 if req.fields and argname in req.fields:
41 results.append(req.fields[argname].value)
48 def abbreviate_time(data):
54 return abbreviate.abbreviate_time(data)
58 return "%dms" % (1000*s)
60 return "%.1fms" % (1000*s)
61 return "%dus" % (1000000*s)
63 def abbreviate_rate(data):
64 # 21.8kBps, 554.4kBps 4.37MBps
69 return "%1.2fMBps" % (r/1000000)
71 return "%.1fkBps" % (r/1000)
74 def abbreviate_size(data):
75 # 21.8kB, 554.4kB 4.37MB
80 return "%1.2fGB" % (r/1000000000)
82 return "%1.2fMB" % (r/1000000)
84 return "%.1fkB" % (r/1000)
87 def plural(sequence_or_length):
88 if isinstance(sequence_or_length, int):
89 length = sequence_or_length
91 length = len(sequence_or_length)
96 def text_plain(text, ctx):
98 req.setHeader("content-type", "text/plain")
99 req.setHeader("content-length", len(text))
102 class WebError(Exception):
103 def __init__(self, text, code=http.BAD_REQUEST):
107 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
108 # Internal Server Error, we either need to do that ICanHandleException trick,
109 # or make sure that childFactory returns a WebErrorResource (and never an
110 # actual exception). The latter is growing increasingly annoying.
112 def should_create_intermediate_directories(req):
113 t = get_arg(req, "t", "").strip()
114 return bool(req.method in ("PUT", "POST") and
115 t not in ("delete", "rename", "rename-form", "check"))
118 class MyExceptionHandler(appserver.DefaultExceptionHandler):
119 def simple(self, ctx, text, code=http.BAD_REQUEST):
121 req.setResponseCode(code)
122 #req.responseHeaders.setRawHeaders("content-encoding", [])
123 #req.responseHeaders.setRawHeaders("content-disposition", [])
124 req.setHeader("content-type", "text/plain;charset=utf-8")
125 if isinstance(text, unicode):
126 text = text.encode("utf-8")
127 req.setHeader("content-length", str(len(text)))
129 # TODO: consider putting the requested URL here
130 req.finishRequest(False)
132 def renderHTTP_exception(self, ctx, f):
133 traceback = f.getTraceback()
134 if f.check(ExistingChildError):
135 return self.simple(ctx,
136 "There was already a child by that "
137 "name, and you asked me to not "
140 elif f.check(NoSuchChildError):
141 name = f.value.args[0]
142 return self.simple(ctx,
143 "No such child: %s" % name.encode("utf-8"),
145 elif f.check(NotEnoughSharesError):
147 needed = f.value.needed
149 t = ("NotEnoughSharesError: no shares could be found. "
150 "Zero shares usually indicates a corrupt URI, or that "
151 "no servers were connected, but it might also indicate "
152 "severe corruption. You should perform a filecheck on "
153 "this object to learn more.")
155 t = ("NotEnoughSharesError: %d share%s found, but we need "
156 "%d to recover the file. This indicates that some "
157 "servers were unavailable, or that shares have been "
158 "lost to server departure, hard drive failure, or disk "
159 "corruption. You should perform a filecheck on "
160 "this object to learn more.") % (got, plural(got), needed)
161 return self.simple(ctx, t, http.GONE)
162 elif f.check(WebError):
163 return self.simple(ctx, f.value.text, f.value.code)
164 elif f.check(FileTooLargeError):
165 return self.simple(ctx, str(f.value), http.REQUEST_ENTITY_TOO_LARGE)
166 elif f.check(server.UnsupportedMethod):
167 # twisted.web.server.Request.render() has support for transforming
168 # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
169 # return code, but nevow does not.
172 return self.simple(ctx,
173 "I don't know how to treat a %s request." % method,
174 http.NOT_IMPLEMENTED)
176 accept = req.getHeader("accept")
179 if "*/*" in accept or "text/*" in accept or "text/html" in accept:
180 super = appserver.DefaultExceptionHandler
181 return super.renderHTTP_exception(self, ctx, f)
183 return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
185 class NeedOperationHandleError(WebError):
190 def renderHTTP(self, ctx):
191 request = IRequest(ctx)
193 # if we were using regular twisted.web Resources (and the regular
194 # twisted.web.server.Request object) then we could implement
195 # render_PUT and render_GET. But Nevow's request handler
196 # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
197 # some code from the Resource.render method that Nevow bypasses, to
199 m = getattr(self, 'render_' + request.method, None)
201 from twisted.web.server import UnsupportedMethod
202 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))