]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/common.py
f4229bb24dad1632f07841ada78c97b79e70faba
[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 def get_filenode_metadata(filenode):
20     metadata = {'mutable': filenode.is_mutable()}
21     if metadata['mutable']:
22         mutable_type = filenode.get_version()
23         assert mutable_type in (SDMF_VERSION, MDMF_VERSION)
24         if mutable_type == MDMF_VERSION:
25             file_format = "MDMF"
26         else:
27             file_format = "SDMF"
28     else:
29         file_format = "CHK"
30     metadata['format'] = file_format
31     size = filenode.get_size()
32     if size is not None:
33         metadata['size'] = size
34     return metadata
35
36 class IOpHandleTable(Interface):
37     pass
38
39 def getxmlfile(name):
40     return loaders.xmlfile(resource_filename('allmydata.web', '%s' % name))
41
42 def boolean_of_arg(arg):
43     # TODO: ""
44     if arg.lower() not in ("true", "t", "1", "false", "f", "0", "on", "off"):
45         raise WebError("invalid boolean argument: %r" % (arg,), http.BAD_REQUEST)
46     return arg.lower() in ("true", "t", "1", "on")
47
48 def parse_replace_arg(replace):
49     if replace.lower() == "only-files":
50         return replace
51     try:
52         return boolean_of_arg(replace)
53     except WebError:
54         raise WebError("invalid replace= argument: %r" % (replace,), http.BAD_REQUEST)
55
56
57 def get_format(req, default="CHK"):
58     arg = get_arg(req, "format", None)
59     if not arg:
60         if boolean_of_arg(get_arg(req, "mutable", "false")):
61             return "SDMF"
62         return default
63     if arg.upper() == "CHK":
64         return "CHK"
65     elif arg.upper() == "SDMF":
66         return "SDMF"
67     elif arg.upper() == "MDMF":
68         return "MDMF"
69     else:
70         raise WebError("Unknown format: %s, I know CHK, SDMF, MDMF" % arg,
71                        http.BAD_REQUEST)
72
73 def get_mutable_type(file_format): # accepts result of get_format()
74     if file_format == "SDMF":
75         return SDMF_VERSION
76     elif file_format == "MDMF":
77         return MDMF_VERSION
78     else:
79         # this is also used to identify which formats are mutable. Use
80         #  if get_mutable_type(file_format) is not None:
81         #      do_mutable()
82         #  else:
83         #      do_immutable()
84         return None
85
86
87 def parse_offset_arg(offset):
88     # XXX: This will raise a ValueError when invoked on something that
89     # is not an integer. Is that okay? Or do we want a better error
90     # message? Since this call is going to be used by programmers and
91     # their tools rather than users (through the wui), it is not
92     # inconsistent to return that, I guess.
93     if offset is not None:
94         offset = int(offset)
95
96     return offset
97
98
99 def get_root(ctx_or_req):
100     req = IRequest(ctx_or_req)
101     # the addSlash=True gives us one extra (empty) segment
102     depth = len(req.prepath) + len(req.postpath) - 1
103     link = "/".join([".."] * depth)
104     return link
105
106 def get_arg(ctx_or_req, argname, default=None, multiple=False):
107     """Extract an argument from either the query args (req.args) or the form
108     body fields (req.fields). If multiple=False, this returns a single value
109     (or the default, which defaults to None), and the query args take
110     precedence. If multiple=True, this returns a tuple of arguments (possibly
111     empty), starting with all those in the query args.
112     """
113     req = IRequest(ctx_or_req)
114     results = []
115     if argname in req.args:
116         results.extend(req.args[argname])
117     if req.fields and argname in req.fields:
118         results.append(req.fields[argname].value)
119     if multiple:
120         return tuple(results)
121     if results:
122         return results[0]
123     return default
124
125 def convert_children_json(nodemaker, children_json):
126     """I convert the JSON output of GET?t=json into the dict-of-nodes input
127     to both dirnode.create_subdirectory() and
128     client.create_directory(initial_children=). This is used by
129     t=mkdir-with-children and t=mkdir-immutable"""
130     children = {}
131     if children_json:
132         data = simplejson.loads(children_json)
133         for (namex, (ctype, propdict)) in data.iteritems():
134             namex = unicode(namex)
135             writecap = to_str(propdict.get("rw_uri"))
136             readcap = to_str(propdict.get("ro_uri"))
137             metadata = propdict.get("metadata", {})
138             # name= argument is just for error reporting
139             childnode = nodemaker.create_from_cap(writecap, readcap, name=namex)
140             children[namex] = (childnode, metadata)
141     return children
142
143 def abbreviate_time(data):
144     # 1.23s, 790ms, 132us
145     if data is None:
146         return ""
147     s = float(data)
148     if s >= 10:
149         return abbreviate.abbreviate_time(data)
150     if s >= 1.0:
151         return "%.2fs" % s
152     if s >= 0.01:
153         return "%.0fms" % (1000*s)
154     if s >= 0.001:
155         return "%.1fms" % (1000*s)
156     return "%.0fus" % (1000000*s)
157
158 def compute_rate(bytes, seconds):
159     if bytes is None:
160       return None
161
162     if seconds is None or seconds == 0:
163       return None
164
165     # negative values don't make sense here
166     assert bytes > -1
167     assert seconds > 0
168
169     return 1.0 * bytes / seconds
170
171 def abbreviate_rate(data):
172     # 21.8kBps, 554.4kBps 4.37MBps
173     if data is None:
174         return ""
175     r = float(data)
176     if r > 1000000:
177         return "%1.2fMBps" % (r/1000000)
178     if r > 1000:
179         return "%.1fkBps" % (r/1000)
180     return "%.0fBps" % r
181
182 def abbreviate_size(data):
183     # 21.8kB, 554.4kB 4.37MB
184     if data is None:
185         return ""
186     r = float(data)
187     if r > 1000000000:
188         return "%1.2fGB" % (r/1000000000)
189     if r > 1000000:
190         return "%1.2fMB" % (r/1000000)
191     if r > 1000:
192         return "%.1fkB" % (r/1000)
193     return "%.0fB" % r
194
195 def plural(sequence_or_length):
196     if isinstance(sequence_or_length, int):
197         length = sequence_or_length
198     else:
199         length = len(sequence_or_length)
200     if length == 1:
201         return ""
202     return "s"
203
204 def text_plain(text, ctx):
205     req = IRequest(ctx)
206     req.setHeader("content-type", "text/plain")
207     req.setHeader("content-length", b"%d" % len(text))
208     return text
209
210 class WebError(Exception):
211     def __init__(self, text, code=http.BAD_REQUEST):
212         self.text = text
213         self.code = code
214
215 # XXX: to make UnsupportedMethod return 501 NOT_IMPLEMENTED instead of 500
216 # Internal Server Error, we either need to do that ICanHandleException trick,
217 # or make sure that childFactory returns a WebErrorResource (and never an
218 # actual exception). The latter is growing increasingly annoying.
219
220 def should_create_intermediate_directories(req):
221     t = get_arg(req, "t", "").strip()
222     return bool(req.method in ("PUT", "POST") and
223                 t not in ("delete", "rename", "rename-form", "check"))
224
225 def humanize_failure(f):
226     # return text, responsecode
227     if f.check(EmptyPathnameComponentError):
228         return ("The webapi does not allow empty pathname components, "
229                 "i.e. a double slash", http.BAD_REQUEST)
230     if f.check(ExistingChildError):
231         return ("There was already a child by that name, and you asked me "
232                 "to not replace it.", http.CONFLICT)
233     if f.check(NoSuchChildError):
234         quoted_name = quote_output(f.value.args[0], encoding="utf-8", quotemarks=False)
235         return ("No such child: %s" % quoted_name, http.NOT_FOUND)
236     if f.check(NotEnoughSharesError):
237         t = ("NotEnoughSharesError: This indicates that some "
238              "servers were unavailable, or that shares have been "
239              "lost to server departure, hard drive failure, or disk "
240              "corruption. You should perform a filecheck on "
241              "this object to learn more.\n\nThe full error message is:\n"
242              "%s") % str(f.value)
243         return (t, http.GONE)
244     if f.check(NoSharesError):
245         t = ("NoSharesError: no shares could be found. "
246              "Zero shares usually indicates a corrupt URI, or that "
247              "no servers were connected, but it might also indicate "
248              "severe corruption. You should perform a filecheck on "
249              "this object to learn more.\n\nThe full error message is:\n"
250              "%s") % str(f.value)
251         return (t, http.GONE)
252     if f.check(UnrecoverableFileError):
253         t = ("UnrecoverableFileError: the directory (or mutable file) could "
254              "not be retrieved, because there were insufficient good shares. "
255              "This might indicate that no servers were connected, "
256              "insufficient servers were connected, the URI was corrupt, or "
257              "that shares have been lost due to server departure, hard drive "
258              "failure, or disk corruption. You should perform a filecheck on "
259              "this object to learn more.")
260         return (t, http.GONE)
261     if f.check(MustNotBeUnknownRWError):
262         quoted_name = quote_output(f.value.args[1], encoding="utf-8")
263         immutable = f.value.args[2]
264         if immutable:
265             t = ("MustNotBeUnknownRWError: an operation to add a child named "
266                  "%s to a directory was given an unknown cap in a write slot.\n"
267                  "If the cap is actually an immutable readcap, then using a "
268                  "webapi server that supports a later version of Tahoe may help.\n\n"
269                  "If you are using the webapi directly, then specifying an immutable "
270                  "readcap in the read slot (ro_uri) of the JSON PROPDICT, and "
271                  "omitting the write slot (rw_uri), would also work in this "
272                  "case.") % quoted_name
273         else:
274             t = ("MustNotBeUnknownRWError: an operation to add a child named "
275                  "%s to a directory was given an unknown cap in a write slot.\n"
276                  "Using a webapi server that supports a later version of Tahoe "
277                  "may help.\n\n"
278                  "If you are using the webapi directly, specifying a readcap in "
279                  "the read slot (ro_uri) of the JSON PROPDICT, as well as a "
280                  "writecap in the write slot if desired, would also work in this "
281                  "case.") % quoted_name
282         return (t, http.BAD_REQUEST)
283     if f.check(MustBeDeepImmutableError):
284         quoted_name = quote_output(f.value.args[1], encoding="utf-8")
285         t = ("MustBeDeepImmutableError: a cap passed to this operation for "
286              "the child named %s, needed to be immutable but was not. Either "
287              "the cap is being added to an immutable directory, or it was "
288              "originally retrieved from an immutable directory as an unknown "
289              "cap.") % quoted_name
290         return (t, http.BAD_REQUEST)
291     if f.check(MustBeReadonlyError):
292         quoted_name = quote_output(f.value.args[1], encoding="utf-8")
293         t = ("MustBeReadonlyError: a cap passed to this operation for "
294              "the child named '%s', needed to be read-only but was not. "
295              "The cap is being passed in a read slot (ro_uri), or was retrieved "
296              "from a read slot as an unknown cap.") % quoted_name
297         return (t, http.BAD_REQUEST)
298     if f.check(blacklist.FileProhibited):
299         t = "Access Prohibited: %s" % quote_output(f.value.reason, encoding="utf-8", quotemarks=False)
300         return (t, http.FORBIDDEN)
301     if f.check(WebError):
302         return (f.value.text, f.value.code)
303     if f.check(FileTooLargeError):
304         return (f.getTraceback(), http.REQUEST_ENTITY_TOO_LARGE)
305     return (str(f), None)
306
307 class MyExceptionHandler(appserver.DefaultExceptionHandler):
308     def simple(self, ctx, text, code=http.BAD_REQUEST):
309         req = IRequest(ctx)
310         req.setResponseCode(code)
311         #req.responseHeaders.setRawHeaders("content-encoding", [])
312         #req.responseHeaders.setRawHeaders("content-disposition", [])
313         req.setHeader("content-type", "text/plain;charset=utf-8")
314         if isinstance(text, unicode):
315             text = text.encode("utf-8")
316         req.setHeader("content-length", b"%d" % len(text))
317         req.write(text)
318         # TODO: consider putting the requested URL here
319         req.finishRequest(False)
320
321     def renderHTTP_exception(self, ctx, f):
322         try:
323             text, code = humanize_failure(f)
324         except:
325             log.msg("exception in humanize_failure")
326             log.msg("argument was %s" % (f,))
327             log.err()
328             text, code = str(f), None
329         if code is not None:
330             return self.simple(ctx, text, code)
331         if f.check(server.UnsupportedMethod):
332             # twisted.web.server.Request.render() has support for transforming
333             # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
334             # return code, but nevow does not.
335             req = IRequest(ctx)
336             method = req.method
337             return self.simple(ctx,
338                                "I don't know how to treat a %s request." % method,
339                                http.NOT_IMPLEMENTED)
340         req = IRequest(ctx)
341         accept = req.getHeader("accept")
342         if not accept:
343             accept = "*/*"
344         if "*/*" in accept or "text/*" in accept or "text/html" in accept:
345             super = appserver.DefaultExceptionHandler
346             return super.renderHTTP_exception(self, ctx, f)
347         # use plain text
348         traceback = f.getTraceback()
349         return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
350
351 class NeedOperationHandleError(WebError):
352     pass
353
354 class RenderMixin:
355
356     def renderHTTP(self, ctx):
357         request = IRequest(ctx)
358
359         # if we were using regular twisted.web Resources (and the regular
360         # twisted.web.server.Request object) then we could implement
361         # render_PUT and render_GET. But Nevow's request handler
362         # (NevowRequest.gotPageContext) goes directly to renderHTTP. Copy
363         # some code from the Resource.render method that Nevow bypasses, to
364         # do the same thing.
365         m = getattr(self, 'render_' + request.method, None)
366         if not m:
367             from twisted.web.server import UnsupportedMethod
368             raise UnsupportedMethod(getattr(self, 'allowedMethods', ()))
369         return m(ctx)