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":
62 def parse_offset_arg(offset):
63 # XXX: This will raise a ValueError when invoked on something that
64 # is not an integer. Is that okay? Or do we want a better error
65 # message? Since this call is going to be used by programmers and
66 # their tools rather than users (through the wui), it is not
67 # inconsistent to return that, I guess.
68 if offset is not None:
74 def get_root(ctx_or_req):
75 req = IRequest(ctx_or_req)
76 # the addSlash=True gives us one extra (empty) segment
77 depth = len(req.prepath) + len(req.postpath) - 1
78 link = "/".join([".."] * depth)
81 def get_arg(ctx_or_req, argname, default=None, multiple=False):
82 """Extract an argument from either the query args (req.args) or the form
83 body fields (req.fields). If multiple=False, this returns a single value
84 (or the default, which defaults to None), and the query args take
85 precedence. If multiple=True, this returns a tuple of arguments (possibly
86 empty), starting with all those in the query args.
88 req = IRequest(ctx_or_req)
90 if argname in req.args:
91 results.extend(req.args[argname])
92 if req.fields and argname in req.fields:
93 results.append(req.fields[argname].value)
100 def convert_children_json(nodemaker, children_json):
101 """I convert the JSON output of GET?t=json into the dict-of-nodes input
102 to both dirnode.create_subdirectory() and
103 client.create_directory(initial_children=). This is used by
104 t=mkdir-with-children and t=mkdir-immutable"""
107 data = simplejson.loads(children_json)
108 for (namex, (ctype, propdict)) in data.iteritems():
109 namex = unicode(namex)
110 writecap = to_str(propdict.get("rw_uri"))
111 readcap = to_str(propdict.get("ro_uri"))
112 metadata = propdict.get("metadata", {})
113 # name= argument is just for error reporting
114 childnode = nodemaker.create_from_cap(writecap, readcap, name=namex)
115 children[namex] = (childnode, metadata)
118 def abbreviate_time(data):
119 # 1.23s, 790ms, 132us
124 return abbreviate.abbreviate_time(data)
128 return "%.0fms" % (1000*s)
130 return "%.1fms" % (1000*s)
131 return "%.0fus" % (1000000*s)
133 def compute_rate(bytes, seconds):
137 if seconds is None or seconds == 0:
140 # negative values don't make sense here
144 return 1.0 * bytes / seconds
146 def abbreviate_rate(data):
147 # 21.8kBps, 554.4kBps 4.37MBps
152 return "%1.2fMBps" % (r/1000000)
154 return "%.1fkBps" % (r/1000)
157 def abbreviate_size(data):
158 # 21.8kB, 554.4kB 4.37MB
163 return "%1.2fGB" % (r/1000000000)
165 return "%1.2fMB" % (r/1000000)
167 return "%.1fkB" % (r/1000)
170 def plural(sequence_or_length):
171 if isinstance(sequence_or_length, int):
172 length = sequence_or_length
174 length = len(sequence_or_length)
179 def text_plain(text, ctx):
181 req.setHeader("content-type", "text/plain")
182 req.setHeader("content-length", len(text))
185 class WebError(Exception):
186 def __init__(self, text, code=http.BAD_REQUEST):
190 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
191 # Internal Server Error, we either need to do that ICanHandleException trick,
192 # or make sure that childFactory returns a WebErrorResource (and never an
193 # actual exception). The latter is growing increasingly annoying.
195 def should_create_intermediate_directories(req):
196 t = get_arg(req, "t", "").strip()
197 return bool(req.method in ("PUT", "POST") and
198 t not in ("delete", "rename", "rename-form", "check"))
200 def humanize_failure(f):
201 # return text, responsecode
202 if f.check(EmptyPathnameComponentError):
203 return ("The webapi does not allow empty pathname components, "
204 "i.e. a double slash", http.BAD_REQUEST)
205 if f.check(ExistingChildError):
206 return ("There was already a child by that name, and you asked me "
207 "to not replace it.", http.CONFLICT)
208 if f.check(NoSuchChildError):
209 quoted_name = quote_output(f.value.args[0], encoding="utf-8", quotemarks=False)
210 return ("No such child: %s" % quoted_name, http.NOT_FOUND)
211 if f.check(NotEnoughSharesError):
212 t = ("NotEnoughSharesError: This indicates that some "
213 "servers were unavailable, or that shares have been "
214 "lost to server departure, hard drive failure, or disk "
215 "corruption. You should perform a filecheck on "
216 "this object to learn more.\n\nThe full error message is:\n"
218 return (t, http.GONE)
219 if f.check(NoSharesError):
220 t = ("NoSharesError: no shares could be found. "
221 "Zero shares usually indicates a corrupt URI, or that "
222 "no servers were connected, but it might also indicate "
223 "severe 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(UnrecoverableFileError):
228 t = ("UnrecoverableFileError: the directory (or mutable file) could "
229 "not be retrieved, because there were insufficient good shares. "
230 "This might indicate that no servers were connected, "
231 "insufficient servers were connected, the URI was corrupt, or "
232 "that shares have been lost due to server departure, hard drive "
233 "failure, or disk corruption. You should perform a filecheck on "
234 "this object to learn more.")
235 return (t, http.GONE)
236 if f.check(MustNotBeUnknownRWError):
237 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
238 immutable = f.value.args[2]
240 t = ("MustNotBeUnknownRWError: an operation to add a child named "
241 "%s to a directory was given an unknown cap in a write slot.\n"
242 "If the cap is actually an immutable readcap, then using a "
243 "webapi server that supports a later version of Tahoe may help.\n\n"
244 "If you are using the webapi directly, then specifying an immutable "
245 "readcap in the read slot (ro_uri) of the JSON PROPDICT, and "
246 "omitting the write slot (rw_uri), would also work in this "
247 "case.") % quoted_name
249 t = ("MustNotBeUnknownRWError: an operation to add a child named "
250 "%s to a directory was given an unknown cap in a write slot.\n"
251 "Using a webapi server that supports a later version of Tahoe "
253 "If you are using the webapi directly, specifying a readcap in "
254 "the read slot (ro_uri) of the JSON PROPDICT, as well as a "
255 "writecap in the write slot if desired, would also work in this "
256 "case.") % quoted_name
257 return (t, http.BAD_REQUEST)
258 if f.check(MustBeDeepImmutableError):
259 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
260 t = ("MustBeDeepImmutableError: a cap passed to this operation for "
261 "the child named %s, needed to be immutable but was not. Either "
262 "the cap is being added to an immutable directory, or it was "
263 "originally retrieved from an immutable directory as an unknown "
264 "cap.") % quoted_name
265 return (t, http.BAD_REQUEST)
266 if f.check(MustBeReadonlyError):
267 quoted_name = quote_output(f.value.args[1], encoding="utf-8")
268 t = ("MustBeReadonlyError: a cap passed to this operation for "
269 "the child named '%s', needed to be read-only but was not. "
270 "The cap is being passed in a read slot (ro_uri), or was retrieved "
271 "from a read slot as an unknown cap.") % quoted_name
272 return (t, http.BAD_REQUEST)
273 if f.check(blacklist.FileProhibited):
274 t = "Access Prohibited: %s" % quote_output(f.value.reason, encoding="utf-8", quotemarks=False)
275 return (t, http.FORBIDDEN)
276 if f.check(WebError):
277 return (f.value.text, f.value.code)
278 if f.check(FileTooLargeError):
279 return (f.getTraceback(), http.REQUEST_ENTITY_TOO_LARGE)
280 return (str(f), None)
282 class MyExceptionHandler(appserver.DefaultExceptionHandler):
283 def simple(self, ctx, text, code=http.BAD_REQUEST):
285 req.setResponseCode(code)
286 #req.responseHeaders.setRawHeaders("content-encoding", [])
287 #req.responseHeaders.setRawHeaders("content-disposition", [])
288 req.setHeader("content-type", "text/plain;charset=utf-8")
289 if isinstance(text, unicode):
290 text = text.encode("utf-8")
291 req.setHeader("content-length", str(len(text)))
293 # TODO: consider putting the requested URL here
294 req.finishRequest(False)
296 def renderHTTP_exception(self, ctx, f):
298 text, code = humanize_failure(f)
300 log.msg("exception in humanize_failure")
301 log.msg("argument was %s" % (f,))
303 text, code = str(f), None
305 return self.simple(ctx, text, code)
306 if f.check(server.UnsupportedMethod):
307 # twisted.web.server.Request.render() has support for transforming
308 # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
309 # return code, but nevow does not.
312 return self.simple(ctx,
313 "I don't know how to treat a %s request." % method,
314 http.NOT_IMPLEMENTED)
316 accept = req.getHeader("accept")
319 if "*/*" in accept or "text/*" in accept or "text/html" in accept:
320 super = appserver.DefaultExceptionHandler
321 return super.renderHTTP_exception(self, ctx, f)
323 traceback = f.getTraceback()
324 return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
326 class NeedOperationHandleError(WebError):
331 def renderHTTP(self, ctx):
332 request = IRequest(ctx)
334 # if we were using regular twisted.web Resources (and the regular
335 # twisted.web.server.Request object) then we could implement
336 # render_PUT and render_GET. But Nevow's request handler
337 # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
338 # some code from the Resource.render method that Nevow bypasses, to
340 m = getattr(self, 'render_' + request.method, None)
342 from twisted.web.server import UnsupportedMethod
343 raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))