5 from twisted.web import http, server
6 from twisted.python import log
7 from zope.interface import Interface
8 from nevow import loaders, appserver
9 from nevow.inevow import IRequest
10 from nevow.util import resource_filename
11 from allmydata import blacklist
12 from allmydata.interfaces import ExistingChildError, NoSuchChildError, \
13 FileTooLargeError, NotEnoughSharesError, NoSharesError, \
14 EmptyPathnameComponentError, MustBeDeepImmutableError, \
15 MustBeReadonlyError, MustNotBeUnknownRWError, SDMF_VERSION, MDMF_VERSION
16 from allmydata.mutable.common import UnrecoverableFileError
17 from allmydata.util import abbreviate
18 from allmydata.util.time_format import format_time
19 from allmydata.util.encodingutil import to_str, quote_output
22 def get_filenode_metadata(filenode):
23 metadata = {'mutable': filenode.is_mutable()}
24 if metadata['mutable']:
25 mutable_type = filenode.get_version()
26 assert mutable_type in (SDMF_VERSION, MDMF_VERSION)
27 if mutable_type == MDMF_VERSION:
33 metadata['format'] = file_format
34 size = filenode.get_size()
36 metadata['size'] = size
39 class IOpHandleTable(Interface):
43 return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
45 def boolean_of_arg(arg):
47 if arg.lower() not in ("true", "t", "1", "false", "f", "0", "on", "off"):
48 raise WebError("invalid boolean argument: %r" % (arg,), http.BAD_REQUEST)
49 return arg.lower() in ("true", "t", "1", "on")
51 def parse_replace_arg(replace):
52 if replace.lower() == "only-files":
55 return boolean_of_arg(replace)
57 raise WebError("invalid replace= argument: %r" % (replace,), http.BAD_REQUEST)
60 def get_format(req, default="CHK"):
61 arg = get_arg(req, "format", None)
63 if boolean_of_arg(get_arg(req, "mutable", "false")):
66 if arg.upper() == "CHK":
68 elif arg.upper() == "SDMF":
70 elif arg.upper() == "MDMF":
73 raise WebError("Unknown format: %s, I know CHK, SDMF, MDMF" % arg,
76 def get_mutable_type(file_format): # accepts result of get_format()
77 if file_format == "SDMF":
79 elif file_format == "MDMF":
82 # this is also used to identify which formats are mutable. Use
83 # if get_mutable_type(file_format) is not None:
90 def parse_offset_arg(offset):
91 # XXX: This will raise a ValueError when invoked on something that
92 # is not an integer. Is that okay? Or do we want a better error
93 # message? Since this call is going to be used by programmers and
94 # their tools rather than users (through the wui), it is not
95 # inconsistent to return that, I guess.
96 if offset is not None:
102 def get_root(ctx_or_req):
103 req = IRequest(ctx_or_req)
104 # the addSlash=True gives us one extra (empty) segment
105 depth = len(req.prepath) + len(req.postpath) - 1
106 link = "/".join([".."] * depth)
109 def get_arg(ctx_or_req, argname, default=None, multiple=False):
110 """Extract an argument from either the query args (req.args) or the form
111 body fields (req.fields). If multiple=False, this returns a single value
112 (or the default, which defaults to None), and the query args take
113 precedence. If multiple=True, this returns a tuple of arguments (possibly
114 empty), starting with all those in the query args.
116 req = IRequest(ctx_or_req)
118 if argname in req.args:
119 results.extend(req.args[argname])
120 if req.fields and argname in req.fields:
121 results.append(req.fields[argname].value)
123 return tuple(results)
128 def convert_children_json(nodemaker, children_json):
129 """I convert the JSON output of GET?t=json into the dict-of-nodes input
130 to both dirnode.create_subdirectory() and
131 client.create_directory(initial_children=). This is used by
132 t=mkdir-with-children and t=mkdir-immutable"""
135 data = simplejson.loads(children_json)
136 for (namex, (ctype, propdict)) in data.iteritems():
137 namex = unicode(namex)
138 writecap = to_str(propdict.get("rw_uri"))
139 readcap = to_str(propdict.get("ro_uri"))
140 metadata = propdict.get("metadata", {})
141 # name= argument is just for error reporting
142 childnode = nodemaker.create_from_cap(writecap, readcap, name=namex)
143 children[namex] = (childnode, metadata)
146 def abbreviate_time(data):
147 # 1.23s, 790ms, 132us
152 return abbreviate.abbreviate_time(data)
156 return "%.0fms" % (1000*s)
158 return "%.1fms" % (1000*s)
159 return "%.0fus" % (1000000*s)
161 def compute_rate(bytes, seconds):
165 if seconds is None or seconds == 0:
168 # negative values don't make sense here
172 return 1.0 * bytes / seconds
174 def abbreviate_rate(data):
175 # 21.8kBps, 554.4kBps 4.37MBps
180 return "%1.2fMBps" % (r/1000000)
182 return "%.1fkBps" % (r/1000)
185 def abbreviate_size(data):
186 # 21.8kB, 554.4kB 4.37MB
191 return "%1.2fGB" % (r/1000000000)
193 return "%1.2fMB" % (r/1000000)
195 return "%.1fkB" % (r/1000)
198 def plural(sequence_or_length):
199 if isinstance(sequence_or_length, int):
200 length = sequence_or_length
202 length = len(sequence_or_length)
207 def text_plain(text, ctx):
209 req.setHeader("content-type", "text/plain")
210 req.setHeader("content-length", b"%d" % len(text))
213 def spaces_to_nbsp(text):
214 return unicode(text).replace(u' ', u'\u00A0')
217 return spaces_to_nbsp(format_time(time.localtime(t)))
219 class WebError(Exception):
220 def __init__(self, text, code=http.BAD_REQUEST):
224 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
225 # Internal Server Error, we either need to do that ICanHandleException trick,
226 # or make sure that childFactory returns a WebErrorResource (and never an
227 # actual exception). The latter is growing increasingly annoying.
229 def should_create_intermediate_directories(req):
230 t = get_arg(req, "t", "").strip()
231 return bool(req.method in ("PUT", "POST") and
232 t not in ("delete", "rename", "rename-form", "check"))
234 def humanize_failure(f):
235 # return text, responsecode
236 if f.check(EmptyPathnameComponentError):
237 return ("The webapi does not allow empty pathname components, "
238 "i.e. a double slash", http.BAD_REQUEST)
239 if f.check(ExistingChildError):
240 return ("There was already a child by that name, and you asked me "
241 "to not replace it.", http.CONFLICT)
242 if f.check(NoSuchChildError):
243 quoted_name = quote_output(f.value.args[0], encoding="utf-8", quotemarks=False)
244 return ("No such child: %s" % quoted_name, http.NOT_FOUND)
245 if f.check(NotEnoughSharesError):
246 t = ("NotEnoughSharesError: This indicates that some "
247 "servers were unavailable, or that shares have been "
248 "lost to server departure, hard drive failure, or disk "
249 "corruption. You should perform a filecheck on "
250 "this object to learn more.\n\nThe full error message is:\n"
252 return (t, http.GONE)
253 if f.check(NoSharesError):
254 t = ("NoSharesError: no shares could be found. "
255 "Zero shares usually indicates a corrupt URI, or that "
256 "no servers were connected, but it might also indicate "
257 "severe corruption. You should perform a filecheck on "
258 "this object to learn more.\n\nThe full error message is:\n"
260 return (t, http.GONE)
261 if f.check(UnrecoverableFileError):
262 t = ("UnrecoverableFileError: the directory (or mutable file) could "
263 "not be retrieved, because there were insufficient good shares. "
264 "This might indicate that no servers were connected, "
265 "insufficient servers were connected, the URI was corrupt, or "
266 "that shares have been lost due to server departure, hard drive "
267 "failure, or disk corruption. You should perform a filecheck on "
268 "this object to learn more.")
269 return (t, http.GONE)
270 if f.check(MustNotBeUnknownRWError):
271 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
272 immutable = f.value.args[2]
274 t = ("MustNotBeUnknownRWError: an operation to add a child named "
275 "%s to a directory was given an unknown cap in a write slot.\n"
276 "If the cap is actually an immutable readcap, then using a "
277 "webapi server that supports a later version of Tahoe may help.\n\n"
278 "If you are using the webapi directly, then specifying an immutable "
279 "readcap in the read slot (ro_uri) of the JSON PROPDICT, and "
280 "omitting the write slot (rw_uri), would also work in this "
281 "case.") % quoted_name
283 t = ("MustNotBeUnknownRWError: an operation to add a child named "
284 "%s to a directory was given an unknown cap in a write slot.\n"
285 "Using a webapi server that supports a later version of Tahoe "
287 "If you are using the webapi directly, specifying a readcap in "
288 "the read slot (ro_uri) of the JSON PROPDICT, as well as a "
289 "writecap in the write slot if desired, would also work in this "
290 "case.") % quoted_name
291 return (t, http.BAD_REQUEST)
292 if f.check(MustBeDeepImmutableError):
293 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
294 t = ("MustBeDeepImmutableError: a cap passed to this operation for "
295 "the child named %s, needed to be immutable but was not. Either "
296 "the cap is being added to an immutable directory, or it was "
297 "originally retrieved from an immutable directory as an unknown "
298 "cap.") % quoted_name
299 return (t, http.BAD_REQUEST)
300 if f.check(MustBeReadonlyError):
301 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
302 t = ("MustBeReadonlyError: a cap passed to this operation for "
303 "the child named '%s', needed to be read-only but was not. "
304 "The cap is being passed in a read slot (ro_uri), or was retrieved "
305 "from a read slot as an unknown cap.") % quoted_name
306 return (t, http.BAD_REQUEST)
307 if f.check(blacklist.FileProhibited):
308 t = "Access Prohibited: %s" % quote_output(f.value.reason, encoding="utf-8", quotemarks=False)
309 return (t, http.FORBIDDEN)
310 if f.check(WebError):
311 return (f.value.text, f.value.code)
312 if f.check(FileTooLargeError):
313 return (f.getTraceback(), http.REQUEST_ENTITY_TOO_LARGE)
314 return (str(f), None)
316 class MyExceptionHandler(appserver.DefaultExceptionHandler):
317 def simple(self, ctx, text, code=http.BAD_REQUEST):
319 req.setResponseCode(code)
320 #req.responseHeaders.setRawHeaders("content-encoding", [])
321 #req.responseHeaders.setRawHeaders("content-disposition", [])
322 req.setHeader("content-type", "text/plain;charset=utf-8")
323 if isinstance(text, unicode):
324 text = text.encode("utf-8")
325 req.setHeader("content-length", b"%d" % len(text))
327 # TODO: consider putting the requested URL here
328 req.finishRequest(False)
330 def renderHTTP_exception(self, ctx, f):
332 text, code = humanize_failure(f)
334 log.msg("exception in humanize_failure")
335 log.msg("argument was %s" % (f,))
337 text, code = str(f), None
339 return self.simple(ctx, text, code)
340 if f.check(server.UnsupportedMethod):
341 # twisted.web.server.Request.render() has support for transforming
342 # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
343 # return code, but nevow does not.
346 return self.simple(ctx,
347 "I don't know how to treat a %s request." % method,
348 http.NOT_IMPLEMENTED)
350 accept = req.getHeader("accept")
353 if "*/*" in accept or "text/*" in accept or "text/html" in accept:
354 super = appserver.DefaultExceptionHandler
355 return super.renderHTTP_exception(self, ctx, f)
357 traceback = f.getTraceback()
358 return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
360 class NeedOperationHandleError(WebError):
365 def renderHTTP(self, ctx):
366 request = IRequest(ctx)
368 # if we were using regular twisted.web Resources (and the regular
369 # twisted.web.server.Request object) then we could implement
370 # render_PUT and render_GET. But Nevow's request handler
371 # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
372 # some code from the Resource.render method that Nevow bypasses, to
374 m = getattr(self, 'render_' + request.method, None)
376 from twisted.web.server import UnsupportedMethod
377 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))