3 from twisted.web import http, server
4 from twisted.python import log
5 from zope.interface import Interface
6 from nevow import loaders, appserver
7 from nevow.inevow import IRequest
8 from nevow.util import resource_filename
9 from allmydata import blacklist
10 from allmydata.interfaces import ExistingChildError, NoSuchChildError, \
11 FileTooLargeError, NotEnoughSharesError, NoSharesError, \
12 EmptyPathnameComponentError, MustBeDeepImmutableError, \
13 MustBeReadonlyError, MustNotBeUnknownRWError, SDMF_VERSION, MDMF_VERSION
14 from allmydata.mutable.common import UnrecoverableFileError
15 from allmydata.util import abbreviate
16 from allmydata.util.encodingutil import to_str, quote_output
19 class IOpHandleTable(Interface):
23 return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
25 def boolean_of_arg(arg):
27 if arg.lower() not in ("true", "t", "1", "false", "f", "0", "on", "off"):
28 raise WebError("invalid boolean argument: %r" % (arg,), http.BAD_REQUEST)
29 return arg.lower() in ("true", "t", "1", "on")
31 def parse_replace_arg(replace):
32 if replace.lower() == "only-files":
35 return boolean_of_arg(replace)
37 raise WebError("invalid replace= argument: %r" % (replace,), http.BAD_REQUEST)
40 def get_format(req, default="CHK"):
41 arg = get_arg(req, "format", None)
43 if boolean_of_arg(get_arg(req, "mutable", "false")):
46 if arg.upper() == "CHK":
48 elif arg.upper() == "SDMF":
50 elif arg.upper() == "MDMF":
53 raise WebError("Unknown format: %s, I know CHK, SDMF, MDMF" % arg,
56 def get_mutable_type(file_format): # accepts result of get_format()
57 if file_format == "SDMF":
59 elif file_format == "MDMF":
62 # this is also used to identify which formats are mutable. Use
63 # if get_mutable_type(file_format) is not None:
70 def parse_offset_arg(offset):
71 # XXX: This will raise a ValueError when invoked on something that
72 # is not an integer. Is that okay? Or do we want a better error
73 # message? Since this call is going to be used by programmers and
74 # their tools rather than users (through the wui), it is not
75 # inconsistent to return that, I guess.
76 if offset is not None:
82 def get_root(ctx_or_req):
83 req = IRequest(ctx_or_req)
84 # the addSlash=True gives us one extra (empty) segment
85 depth = len(req.prepath) + len(req.postpath) - 1
86 link = "/".join([".."] * depth)
89 def get_arg(ctx_or_req, argname, default=None, multiple=False):
90 """Extract an argument from either the query args (req.args) or the form
91 body fields (req.fields). If multiple=False, this returns a single value
92 (or the default, which defaults to None), and the query args take
93 precedence. If multiple=True, this returns a tuple of arguments (possibly
94 empty), starting with all those in the query args.
96 req = IRequest(ctx_or_req)
98 if argname in req.args:
99 results.extend(req.args[argname])
100 if req.fields and argname in req.fields:
101 results.append(req.fields[argname].value)
103 return tuple(results)
108 def convert_children_json(nodemaker, children_json):
109 """I convert the JSON output of GET?t=json into the dict-of-nodes input
110 to both dirnode.create_subdirectory() and
111 client.create_directory(initial_children=). This is used by
112 t=mkdir-with-children and t=mkdir-immutable"""
115 data = simplejson.loads(children_json)
116 for (namex, (ctype, propdict)) in data.iteritems():
117 namex = unicode(namex)
118 writecap = to_str(propdict.get("rw_uri"))
119 readcap = to_str(propdict.get("ro_uri"))
120 metadata = propdict.get("metadata", {})
121 # name= argument is just for error reporting
122 childnode = nodemaker.create_from_cap(writecap, readcap, name=namex)
123 children[namex] = (childnode, metadata)
126 def abbreviate_time(data):
127 # 1.23s, 790ms, 132us
132 return abbreviate.abbreviate_time(data)
136 return "%.0fms" % (1000*s)
138 return "%.1fms" % (1000*s)
139 return "%.0fus" % (1000000*s)
141 def compute_rate(bytes, seconds):
145 if seconds is None or seconds == 0:
148 # negative values don't make sense here
152 return 1.0 * bytes / seconds
154 def abbreviate_rate(data):
155 # 21.8kBps, 554.4kBps 4.37MBps
160 return "%1.2fMBps" % (r/1000000)
162 return "%.1fkBps" % (r/1000)
165 def abbreviate_size(data):
166 # 21.8kB, 554.4kB 4.37MB
171 return "%1.2fGB" % (r/1000000000)
173 return "%1.2fMB" % (r/1000000)
175 return "%.1fkB" % (r/1000)
178 def plural(sequence_or_length):
179 if isinstance(sequence_or_length, int):
180 length = sequence_or_length
182 length = len(sequence_or_length)
187 def text_plain(text, ctx):
189 req.setHeader("content-type", "text/plain")
190 req.setHeader("content-length", len(text))
193 class WebError(Exception):
194 def __init__(self, text, code=http.BAD_REQUEST):
198 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
199 # Internal Server Error, we either need to do that ICanHandleException trick,
200 # or make sure that childFactory returns a WebErrorResource (and never an
201 # actual exception). The latter is growing increasingly annoying.
203 def should_create_intermediate_directories(req):
204 t = get_arg(req, "t", "").strip()
205 return bool(req.method in ("PUT", "POST") and
206 t not in ("delete", "rename", "rename-form", "check"))
208 def humanize_failure(f):
209 # return text, responsecode
210 if f.check(EmptyPathnameComponentError):
211 return ("The webapi does not allow empty pathname components, "
212 "i.e. a double slash", http.BAD_REQUEST)
213 if f.check(ExistingChildError):
214 return ("There was already a child by that name, and you asked me "
215 "to not replace it.", http.CONFLICT)
216 if f.check(NoSuchChildError):
217 quoted_name = quote_output(f.value.args[0], encoding="utf-8", quotemarks=False)
218 return ("No such child: %s" % quoted_name, http.NOT_FOUND)
219 if f.check(NotEnoughSharesError):
220 t = ("NotEnoughSharesError: This indicates that some "
221 "servers were unavailable, or that shares have been "
222 "lost to server departure, hard drive failure, or disk "
223 "corruption. You should perform a filecheck on "
224 "this object to learn more.\n\nThe full error message is:\n"
226 return (t, http.GONE)
227 if f.check(NoSharesError):
228 t = ("NoSharesError: no shares could be found. "
229 "Zero shares usually indicates a corrupt URI, or that "
230 "no servers were connected, but it might also indicate "
231 "severe corruption. You should perform a filecheck on "
232 "this object to learn more.\n\nThe full error message is:\n"
234 return (t, http.GONE)
235 if f.check(UnrecoverableFileError):
236 t = ("UnrecoverableFileError: the directory (or mutable file) could "
237 "not be retrieved, because there were insufficient good shares. "
238 "This might indicate that no servers were connected, "
239 "insufficient servers were connected, the URI was corrupt, or "
240 "that shares have been lost due to server departure, hard drive "
241 "failure, or disk corruption. You should perform a filecheck on "
242 "this object to learn more.")
243 return (t, http.GONE)
244 if f.check(MustNotBeUnknownRWError):
245 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
246 immutable = f.value.args[2]
248 t = ("MustNotBeUnknownRWError: an operation to add a child named "
249 "%s to a directory was given an unknown cap in a write slot.\n"
250 "If the cap is actually an immutable readcap, then using a "
251 "webapi server that supports a later version of Tahoe may help.\n\n"
252 "If you are using the webapi directly, then specifying an immutable "
253 "readcap in the read slot (ro_uri) of the JSON PROPDICT, and "
254 "omitting the write slot (rw_uri), would also work in this "
255 "case.") % quoted_name
257 t = ("MustNotBeUnknownRWError: an operation to add a child named "
258 "%s to a directory was given an unknown cap in a write slot.\n"
259 "Using a webapi server that supports a later version of Tahoe "
261 "If you are using the webapi directly, specifying a readcap in "
262 "the read slot (ro_uri) of the JSON PROPDICT, as well as a "
263 "writecap in the write slot if desired, would also work in this "
264 "case.") % quoted_name
265 return (t, http.BAD_REQUEST)
266 if f.check(MustBeDeepImmutableError):
267 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
268 t = ("MustBeDeepImmutableError: a cap passed to this operation for "
269 "the child named %s, needed to be immutable but was not. Either "
270 "the cap is being added to an immutable directory, or it was "
271 "originally retrieved from an immutable directory as an unknown "
272 "cap.") % quoted_name
273 return (t, http.BAD_REQUEST)
274 if f.check(MustBeReadonlyError):
275 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
276 t = ("MustBeReadonlyError: a cap passed to this operation for "
277 "the child named '%s', needed to be read-only but was not. "
278 "The cap is being passed in a read slot (ro_uri), or was retrieved "
279 "from a read slot as an unknown cap.") % quoted_name
280 return (t, http.BAD_REQUEST)
281 if f.check(blacklist.FileProhibited):
282 t = "Access Prohibited: %s" % quote_output(f.value.reason, encoding="utf-8", quotemarks=False)
283 return (t, http.FORBIDDEN)
284 if f.check(WebError):
285 return (f.value.text, f.value.code)
286 if f.check(FileTooLargeError):
287 return (f.getTraceback(), http.REQUEST_ENTITY_TOO_LARGE)
288 return (str(f), None)
290 class MyExceptionHandler(appserver.DefaultExceptionHandler):
291 def simple(self, ctx, text, code=http.BAD_REQUEST):
293 req.setResponseCode(code)
294 #req.responseHeaders.setRawHeaders("content-encoding", [])
295 #req.responseHeaders.setRawHeaders("content-disposition", [])
296 req.setHeader("content-type", "text/plain;charset=utf-8")
297 if isinstance(text, unicode):
298 text = text.encode("utf-8")
299 req.setHeader("content-length", str(len(text)))
301 # TODO: consider putting the requested URL here
302 req.finishRequest(False)
304 def renderHTTP_exception(self, ctx, f):
306 text, code = humanize_failure(f)
308 log.msg("exception in humanize_failure")
309 log.msg("argument was %s" % (f,))
311 text, code = str(f), None
313 return self.simple(ctx, text, code)
314 if f.check(server.UnsupportedMethod):
315 # twisted.web.server.Request.render() has support for transforming
316 # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
317 # return code, but nevow does not.
320 return self.simple(ctx,
321 "I don't know how to treat a %s request." % method,
322 http.NOT_IMPLEMENTED)
324 accept = req.getHeader("accept")
327 if "*/*" in accept or "text/*" in accept or "text/html" in accept:
328 super = appserver.DefaultExceptionHandler
329 return super.renderHTTP_exception(self, ctx, f)
331 traceback = f.getTraceback()
332 return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
334 class NeedOperationHandleError(WebError):
339 def renderHTTP(self, ctx):
340 request = IRequest(ctx)
342 # if we were using regular twisted.web Resources (and the regular
343 # twisted.web.server.Request object) then we could implement
344 # render_PUT and render_GET. But Nevow's request handler
345 # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
346 # some code from the Resource.render method that Nevow bypasses, to
348 m = getattr(self, 'render_' + request.method, None)
350 from twisted.web.server import UnsupportedMethod
351 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))