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