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