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