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