]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/common.py
webapi: handle format=, remove mutable-type=
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / web / common.py
1
2 import simplejson
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
17
18
19 class IOpHandleTable(Interface):
20     pass
21
22 def getxmlfile(name):
23     return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
24
25 def boolean_of_arg(arg):
26     # TODO: ""
27     assert arg.lower() in ("true", "t", "1", "false", "f", "0", "on", "off")
28     return arg.lower() in ("true", "t", "1", "on")
29
30 def parse_replace_arg(replace):
31     if replace.lower() == "only-files":
32         return replace
33     else:
34         return boolean_of_arg(replace)
35
36
37 def get_format(req, default="CHK"):
38     arg = get_arg(req, "format", None)
39     if not arg:
40         if boolean_of_arg(get_arg(req, "mutable", "false")):
41             return "SDMF"
42         return default
43     if arg.upper() == "CHK":
44         return "CHK"
45     elif arg.upper() == "SDMF":
46         return "SDMF"
47     elif arg.upper() == "MDMF":
48         return "MDMF"
49     else:
50         raise WebError("Unknown format: %s, I know CHK, SDMF, MDMF" % arg,
51                        http.BAD_REQUEST)
52
53 def get_mutable_type(file_format): # accepts result of get_format()
54     if file_format == "SDMF":
55         return SDMF_VERSION
56     elif file_format == "MDMF":
57         return MDMF_VERSION
58     else:
59         return None
60
61
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:
69         offset = int(offset)
70
71     return offset
72
73
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)
79     return link
80
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.
87     """
88     req = IRequest(ctx_or_req)
89     results = []
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)
94     if multiple:
95         return tuple(results)
96     if results:
97         return results[0]
98     return default
99
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"""
105     children = {}
106     if children_json:
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)
116     return children
117
118 def abbreviate_time(data):
119     # 1.23s, 790ms, 132us
120     if data is None:
121         return ""
122     s = float(data)
123     if s >= 10:
124         return abbreviate.abbreviate_time(data)
125     if s >= 1.0:
126         return "%.2fs" % s
127     if s >= 0.01:
128         return "%.0fms" % (1000*s)
129     if s >= 0.001:
130         return "%.1fms" % (1000*s)
131     return "%.0fus" % (1000000*s)
132
133 def compute_rate(bytes, seconds):
134     if bytes is None:
135       return None
136
137     if seconds is None or seconds == 0:
138       return None
139
140     # negative values don't make sense here
141     assert bytes > -1
142     assert seconds > 0
143
144     return 1.0 * bytes / seconds
145
146 def abbreviate_rate(data):
147     # 21.8kBps, 554.4kBps 4.37MBps
148     if data is None:
149         return ""
150     r = float(data)
151     if r > 1000000:
152         return "%1.2fMBps" % (r/1000000)
153     if r > 1000:
154         return "%.1fkBps" % (r/1000)
155     return "%.0fBps" % r
156
157 def abbreviate_size(data):
158     # 21.8kB, 554.4kB 4.37MB
159     if data is None:
160         return ""
161     r = float(data)
162     if r > 1000000000:
163         return "%1.2fGB" % (r/1000000000)
164     if r > 1000000:
165         return "%1.2fMB" % (r/1000000)
166     if r > 1000:
167         return "%.1fkB" % (r/1000)
168     return "%.0fB" % r
169
170 def plural(sequence_or_length):
171     if isinstance(sequence_or_length, int):
172         length = sequence_or_length
173     else:
174         length = len(sequence_or_length)
175     if length == 1:
176         return ""
177     return "s"
178
179 def text_plain(text, ctx):
180     req = IRequest(ctx)
181     req.setHeader("content-type", "text/plain")
182     req.setHeader("content-length", len(text))
183     return text
184
185 class WebError(Exception):
186     def __init__(self, text, code=http.BAD_REQUEST):
187         self.text = text
188         self.code = code
189
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.
194
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"))
199
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"
217              "%s") % str(f.value)
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"
225              "%s") % str(f.value)
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]
239         if immutable:
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
248         else:
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 "
252                  "may help.\n\n"
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)
281
282 class MyExceptionHandler(appserver.DefaultExceptionHandler):
283     def simple(self, ctx, text, code=http.BAD_REQUEST):
284         req = IRequest(ctx)
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)))
292         req.write(text)
293         # TODO: consider putting the requested URL here
294         req.finishRequest(False)
295
296     def renderHTTP_exception(self, ctx, f):
297         try:
298             text, code = humanize_failure(f)
299         except:
300             log.msg("exception in humanize_failure")
301             log.msg("argument was %s" % (f,))
302             log.err()
303             text, code = str(f), None
304         if code is not 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.
310             req = IRequest(ctx)
311             method = req.method
312             return self.simple(ctx,
313                                "I don't know how to treat a %s request." % method,
314                                http.NOT_IMPLEMENTED)
315         req = IRequest(ctx)
316         accept = req.getHeader("accept")
317         if not accept:
318             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)
322         # use plain text
323         traceback = f.getTraceback()
324         return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
325
326 class NeedOperationHandleError(WebError):
327     pass
328
329 class RenderMixin:
330
331     def renderHTTP(self, ctx):
332         request = IRequest(ctx)
333
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
339         # do the same thing.
340         m = getattr(self, 'render_' + request.method, None)
341         if not m:
342             from twisted.web.server import UnsupportedMethod
343             raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))
344         return m(ctx)