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