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 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
22 class IOpHandleTable(Interface):
26 return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
28 def boolean_of_arg(arg):
30 if arg.lower() not in ("true", "t", "1", "false", "f", "0", "on", "off"):
31 raise WebError("invalid boolean argument: %r" % (arg,), http.BAD_REQUEST)
32 return arg.lower() in ("true", "t", "1", "on")
34 def parse_replace_arg(replace):
35 if replace.lower() == "only-files":
38 return boolean_of_arg(replace)
40 raise WebError("invalid replace= argument: %r" % (replace,), http.BAD_REQUEST)
43 def get_format(req, default="CHK"):
44 arg = get_arg(req, "format", None)
46 if boolean_of_arg(get_arg(req, "mutable", "false")):
49 if arg.upper() == "CHK":
51 elif arg.upper() == "SDMF":
53 elif arg.upper() == "MDMF":
56 raise WebError("Unknown format: %s, I know CHK, SDMF, MDMF" % arg,
59 def get_mutable_type(file_format): # accepts result of get_format()
60 if file_format == "SDMF":
62 elif file_format == "MDMF":
65 # this is also used to identify which formats are mutable. Use
66 # if get_mutable_type(file_format) is not None:
73 def parse_offset_arg(offset):
74 # XXX: This will raise a ValueError when invoked on something that
75 # is not an integer. Is that okay? Or do we want a better error
76 # message? Since this call is going to be used by programmers and
77 # their tools rather than users (through the wui), it is not
78 # inconsistent to return that, I guess.
79 if offset is not None:
85 def get_root(ctx_or_req):
86 req = IRequest(ctx_or_req)
87 # the addSlash=True gives us one extra (empty) segment
88 depth = len(req.prepath) + len(req.postpath) - 1
89 link = "/".join([".."] * depth)
92 def get_arg(ctx_or_req, argname, default=None, multiple=False):
93 """Extract an argument from either the query args (req.args) or the form
94 body fields (req.fields). If multiple=False, this returns a single value
95 (or the default, which defaults to None), and the query args take
96 precedence. If multiple=True, this returns a tuple of arguments (possibly
97 empty), starting with all those in the query args.
99 req = IRequest(ctx_or_req)
101 if argname in req.args:
102 results.extend(req.args[argname])
103 if req.fields and argname in req.fields:
104 results.append(req.fields[argname].value)
106 return tuple(results)
111 def convert_children_json(nodemaker, children_json):
112 """I convert the JSON output of GET?t=json into the dict-of-nodes input
113 to both dirnode.create_subdirectory() and
114 client.create_directory(initial_children=). This is used by
115 t=mkdir-with-children and t=mkdir-immutable"""
118 data = simplejson.loads(children_json)
119 for (namex, (ctype, propdict)) in data.iteritems():
120 namex = unicode(namex)
121 writecap = to_str(propdict.get("rw_uri"))
122 readcap = to_str(propdict.get("ro_uri"))
123 metadata = propdict.get("metadata", {})
124 # name= argument is just for error reporting
125 childnode = nodemaker.create_from_cap(writecap, readcap, name=namex)
126 children[namex] = (childnode, metadata)
129 def abbreviate_time(data):
130 # 1.23s, 790ms, 132us
135 return abbreviate.abbreviate_time(data)
139 return "%.0fms" % (1000*s)
141 return "%.1fms" % (1000*s)
142 return "%.0fus" % (1000000*s)
144 def compute_rate(bytes, seconds):
148 if seconds is None or seconds == 0:
151 # negative values don't make sense here
155 return 1.0 * bytes / seconds
157 def abbreviate_rate(data):
158 # 21.8kBps, 554.4kBps 4.37MBps
163 return "%1.2fMBps" % (r/1000000)
165 return "%.1fkBps" % (r/1000)
168 def abbreviate_size(data):
169 # 21.8kB, 554.4kB 4.37MB
174 return "%1.2fGB" % (r/1000000000)
176 return "%1.2fMB" % (r/1000000)
178 return "%.1fkB" % (r/1000)
181 def plural(sequence_or_length):
182 if isinstance(sequence_or_length, int):
183 length = sequence_or_length
185 length = len(sequence_or_length)
190 def text_plain(text, ctx):
192 req.setHeader("content-type", "text/plain")
193 req.setHeader("content-length", len(text))
196 class WebError(Exception):
197 def __init__(self, text, code=http.BAD_REQUEST):
201 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
202 # Internal Server Error, we either need to do that ICanHandleException trick,
203 # or make sure that childFactory returns a WebErrorResource (and never an
204 # actual exception). The latter is growing increasingly annoying.
206 def should_create_intermediate_directories(req):
207 t = get_arg(req, "t", "").strip()
208 return bool(req.method in ("PUT", "POST") and
209 t not in ("delete", "rename", "rename-form", "check"))
211 def humanize_failure(f):
212 # return text, responsecode
213 if f.check(EmptyPathnameComponentError):
214 return ("The webapi does not allow empty pathname components, "
215 "i.e. a double slash", http.BAD_REQUEST)
216 if f.check(ExistingChildError):
217 return ("There was already a child by that name, and you asked me "
218 "to not replace it.", http.CONFLICT)
219 if f.check(NoSuchChildError):
220 quoted_name = quote_output(f.value.args[0], encoding="utf-8", quotemarks=False)
221 return ("No such child: %s" % quoted_name, http.NOT_FOUND)
222 if f.check(NotEnoughSharesError):
223 t = ("NotEnoughSharesError: This indicates that some "
224 "servers were unavailable, or that shares have been "
225 "lost to server departure, hard drive failure, or disk "
226 "corruption. You should perform a filecheck on "
227 "this object to learn more.\n\nThe full error message is:\n"
229 return (t, http.GONE)
230 if f.check(NoSharesError):
231 t = ("NoSharesError: no shares could be found. "
232 "Zero shares usually indicates a corrupt URI, or that "
233 "no servers were connected, but it might also indicate "
234 "severe corruption. You should perform a filecheck on "
235 "this object to learn more.\n\nThe full error message is:\n"
237 return (t, http.GONE)
238 if f.check(UnrecoverableFileError):
239 t = ("UnrecoverableFileError: the directory (or mutable file) could "
240 "not be retrieved, because there were insufficient good shares. "
241 "This might indicate that no servers were connected, "
242 "insufficient servers were connected, the URI was corrupt, or "
243 "that shares have been lost due to server departure, hard drive "
244 "failure, or disk corruption. You should perform a filecheck on "
245 "this object to learn more.")
246 return (t, http.GONE)
247 if f.check(MustNotBeUnknownRWError):
248 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
249 immutable = f.value.args[2]
251 t = ("MustNotBeUnknownRWError: an operation to add a child named "
252 "%s to a directory was given an unknown cap in a write slot.\n"
253 "If the cap is actually an immutable readcap, then using a "
254 "webapi server that supports a later version of Tahoe may help.\n\n"
255 "If you are using the webapi directly, then specifying an immutable "
256 "readcap in the read slot (ro_uri) of the JSON PROPDICT, and "
257 "omitting the write slot (rw_uri), would also work in this "
258 "case.") % quoted_name
260 t = ("MustNotBeUnknownRWError: an operation to add a child named "
261 "%s to a directory was given an unknown cap in a write slot.\n"
262 "Using a webapi server that supports a later version of Tahoe "
264 "If you are using the webapi directly, specifying a readcap in "
265 "the read slot (ro_uri) of the JSON PROPDICT, as well as a "
266 "writecap in the write slot if desired, would also work in this "
267 "case.") % quoted_name
268 return (t, http.BAD_REQUEST)
269 if f.check(MustBeDeepImmutableError):
270 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
271 t = ("MustBeDeepImmutableError: a cap passed to this operation for "
272 "the child named %s, needed to be immutable but was not. Either "
273 "the cap is being added to an immutable directory, or it was "
274 "originally retrieved from an immutable directory as an unknown "
275 "cap.") % quoted_name
276 return (t, http.BAD_REQUEST)
277 if f.check(MustBeReadonlyError):
278 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
279 t = ("MustBeReadonlyError: a cap passed to this operation for "
280 "the child named '%s', needed to be read-only but was not. "
281 "The cap is being passed in a read slot (ro_uri), or was retrieved "
282 "from a read slot as an unknown cap.") % quoted_name
283 return (t, http.BAD_REQUEST)
284 if f.check(blacklist.FileProhibited):
285 t = "Access Prohibited: %s" % quote_output(f.value.reason, encoding="utf-8", quotemarks=False)
286 return (t, http.FORBIDDEN)
287 if f.check(WebError):
288 return (f.value.text, f.value.code)
289 if f.check(FileTooLargeError):
290 return (f.getTraceback(), http.REQUEST_ENTITY_TOO_LARGE)
291 return (str(f), None)
293 class MyExceptionHandler(appserver.DefaultExceptionHandler):
294 def simple(self, ctx, text, code=http.BAD_REQUEST):
296 req.setResponseCode(code)
297 #req.responseHeaders.setRawHeaders("content-encoding", [])
298 #req.responseHeaders.setRawHeaders("content-disposition", [])
299 req.setHeader("content-type", "text/plain;charset=utf-8")
300 if isinstance(text, unicode):
301 text = text.encode("utf-8")
302 req.setHeader("content-length", str(len(text)))
304 # TODO: consider putting the requested URL here
305 req.finishRequest(False)
307 def renderHTTP_exception(self, ctx, f):
309 text, code = humanize_failure(f)
311 log.msg("exception in humanize_failure")
312 log.msg("argument was %s" % (f,))
314 text, code = str(f), None
316 return self.simple(ctx, text, code)
317 if f.check(server.UnsupportedMethod):
318 # twisted.web.server.Request.render() has support for transforming
319 # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
320 # return code, but nevow does not.
323 return self.simple(ctx,
324 "I don't know how to treat a %s request." % method,
325 http.NOT_IMPLEMENTED)
327 accept = req.getHeader("accept")
330 if "*/*" in accept or "text/*" in accept or "text/html" in accept:
331 super = appserver.DefaultExceptionHandler
332 return super.renderHTTP_exception(self, ctx, f)
334 traceback = f.getTraceback()
335 return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
337 class NeedOperationHandleError(WebError):
342 def renderHTTP(self, ctx):
343 request = IRequest(ctx)
345 # if we were using regular twisted.web Resources (and the regular
346 # twisted.web.server.Request object) then we could implement
347 # render_PUT and render_GET. But Nevow's request handler
348 # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
349 # some code from the Resource.render method that Nevow bypasses, to
351 m = getattr(self, 'render_' + request.method, None)
353 from twisted.web.server import UnsupportedMethod
354 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))