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