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