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