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