]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/web/root.py
web: make sure that PUT /uri?mutable=false really means immutable, fixes #675
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / web / root.py
1 import time
2
3 from twisted.internet import address
4 from twisted.web import http
5 from nevow import rend, url, loaders, tags as T
6 from nevow.inevow import IRequest
7 from nevow.static import File as nevow_File # TODO: merge with static.File?
8 from nevow.util import resource_filename
9 from formless import webform
10
11 import allmydata # to display import path
12 from allmydata import get_package_versions_string
13 from allmydata import provisioning
14 from allmydata.util import idlib, log
15 from allmydata.interfaces import IFileNode
16 from allmydata.web import filenode, directory, unlinked, status, operations
17 from allmydata.web import reliability, storage
18 from allmydata.web.common import abbreviate_size, getxmlfile, WebError, \
19      get_arg, RenderMixin, boolean_of_arg
20
21
22 class URIHandler(RenderMixin, rend.Page):
23     # I live at /uri . There are several operations defined on /uri itself,
24     # mostly involved with creation of unlinked files and directories.
25
26     def __init__(self, client):
27         rend.Page.__init__(self, client)
28         self.client = client
29
30     def render_GET(self, ctx):
31         req = IRequest(ctx)
32         uri = get_arg(req, "uri", None)
33         if uri is None:
34             raise WebError("GET /uri requires uri=")
35         there = url.URL.fromContext(ctx)
36         there = there.clear("uri")
37         # I thought about escaping the childcap that we attach to the URL
38         # here, but it seems that nevow does that for us.
39         there = there.child(uri)
40         return there
41
42     def render_PUT(self, ctx):
43         req = IRequest(ctx)
44         # either "PUT /uri" to create an unlinked file, or
45         # "PUT /uri?t=mkdir" to create an unlinked directory
46         t = get_arg(req, "t", "").strip()
47         if t == "":
48             mutable = boolean_of_arg(get_arg(req, "mutable", "false").strip())
49             if mutable:
50                 return unlinked.PUTUnlinkedSSK(req, self.client)
51             else:
52                 return unlinked.PUTUnlinkedCHK(req, self.client)
53         if t == "mkdir":
54             return unlinked.PUTUnlinkedCreateDirectory(req, self.client)
55         errmsg = ("/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, "
56                   "and POST?t=mkdir")
57         raise WebError(errmsg, http.BAD_REQUEST)
58
59     def render_POST(self, ctx):
60         # "POST /uri?t=upload&file=newfile" to upload an
61         # unlinked file or "POST /uri?t=mkdir" to create a
62         # new directory
63         req = IRequest(ctx)
64         t = get_arg(req, "t", "").strip()
65         if t in ("", "upload"):
66             mutable = bool(get_arg(req, "mutable", "").strip())
67             if mutable:
68                 return unlinked.POSTUnlinkedSSK(req, self.client)
69             else:
70                 return unlinked.POSTUnlinkedCHK(req, self.client)
71         if t == "mkdir":
72             return unlinked.POSTUnlinkedCreateDirectory(req, self.client)
73         errmsg = ("/uri accepts only PUT, PUT?t=mkdir, POST?t=upload, "
74                   "and POST?t=mkdir")
75         raise WebError(errmsg, http.BAD_REQUEST)
76
77     def childFactory(self, ctx, name):
78         # 'name' is expected to be a URI
79         try:
80             node = self.client.create_node_from_uri(name)
81             return directory.make_handler_for(node, self.client)
82         except (TypeError, AssertionError):
83             raise WebError("'%s' is not a valid file- or directory- cap"
84                            % name)
85
86 class FileHandler(rend.Page):
87     # I handle /file/$FILECAP[/IGNORED] , which provides a URL from which a
88     # file can be downloaded correctly by tools like "wget".
89
90     def __init__(self, client):
91         rend.Page.__init__(self, client)
92         self.client = client
93
94     def childFactory(self, ctx, name):
95         req = IRequest(ctx)
96         if req.method not in ("GET", "HEAD"):
97             raise WebError("/file can only be used with GET or HEAD")
98         # 'name' must be a file URI
99         try:
100             node = self.client.create_node_from_uri(name)
101         except (TypeError, AssertionError):
102             raise WebError("'%s' is not a valid file- or directory- cap"
103                            % name)
104         if not IFileNode.providedBy(node):
105             raise WebError("'%s' is not a file-cap" % name)
106         return filenode.FileNodeDownloadHandler(self.client, node)
107
108     def renderHTTP(self, ctx):
109         raise WebError("/file must be followed by a file-cap and a name",
110                        http.NOT_FOUND)
111
112 class IncidentReporter(RenderMixin, rend.Page):
113     def render_POST(self, ctx):
114         req = IRequest(ctx)
115         log.msg(format="User reports incident through web page: %(details)s",
116                 details=get_arg(req, "details", ""),
117                 level=log.WEIRD, umid="LkD9Pw")
118         req.setHeader("content-type", "text/plain")
119         return "Thank you for your report!"
120
121 class NoReliability(rend.Page):
122     docFactory = loaders.xmlstr('''\
123 <html xmlns:n="http://nevow.com/ns/nevow/0.1">
124   <head>
125     <title>AllMyData - Tahoe</title>
126     <link href="/webform_css" rel="stylesheet" type="text/css"/>
127     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
128   </head>
129   <body>
130   <h2>"Reliability" page not available</h2>
131   <p>Please install the python "NumPy" module to enable this page.</p>
132   </body>
133 </html>
134 ''')
135
136 class Root(rend.Page):
137
138     addSlash = True
139     docFactory = getxmlfile("welcome.xhtml")
140
141     def __init__(self, client):
142         rend.Page.__init__(self, client)
143         self.client = client
144         self.child_operations = operations.OphandleTable()
145         try:
146             s = client.getServiceNamed("storage")
147         except KeyError:
148             s = None
149         self.child_storage = storage.StorageStatus(s)
150
151         self.child_uri = URIHandler(client)
152         self.child_cap = URIHandler(client)
153
154         self.child_file = FileHandler(client)
155         self.child_named = FileHandler(client)
156         self.child_status = status.Status(client) # TODO: use client.history
157         self.child_statistics = status.Statistics(client.stats_provider)
158
159     def child_helper_status(self, ctx):
160         # the Helper isn't attached until after the Tub starts, so this child
161         # needs to created on each request
162         try:
163             helper = self.client.getServiceNamed("helper")
164         except KeyError:
165             helper = None
166         return status.HelperStatus(helper)
167
168     child_webform_css = webform.defaultCSS
169     child_tahoe_css = nevow_File(resource_filename('allmydata.web', 'tahoe.css'))
170
171     child_provisioning = provisioning.ProvisioningTool()
172     if reliability.is_available():
173         child_reliability = reliability.ReliabilityTool()
174     else:
175         child_reliability = NoReliability()
176
177     child_report_incident = IncidentReporter()
178     #child_server # let's reserve this for storage-server-over-HTTP
179
180     def data_version(self, ctx, data):
181         return get_package_versions_string()
182     def data_import_path(self, ctx, data):
183         return str(allmydata)
184     def data_my_nodeid(self, ctx, data):
185         return idlib.nodeid_b2a(self.client.nodeid)
186     def data_my_nickname(self, ctx, data):
187         return self.client.nickname
188
189     def render_services(self, ctx, data):
190         ul = T.ul()
191         try:
192             ss = self.client.getServiceNamed("storage")
193             stats = ss.get_stats()
194             if stats["storage_server.accepting_immutable_shares"]:
195                 msg = "accepting new shares"
196             else:
197                 msg = "not accepting new shares (read-only)"
198             available = stats.get("storage_server.disk_avail")
199             if available is not None:
200                 msg += ", %s available" % abbreviate_size(available)
201             ul[T.li[T.a(href="storage")["Storage Server"], ": ", msg]]
202         except KeyError:
203             ul[T.li["Not running storage server"]]
204
205         try:
206             h = self.client.getServiceNamed("helper")
207             stats = h.get_stats()
208             active_uploads = stats["chk_upload_helper.active_uploads"]
209             ul[T.li["Helper: %d active uploads" % (active_uploads,)]]
210         except KeyError:
211             ul[T.li["Not running helper"]]
212
213         return ctx.tag[ul]
214
215     def data_introducer_furl(self, ctx, data):
216         return self.client.introducer_furl
217     def data_connected_to_introducer(self, ctx, data):
218         if self.client.connected_to_introducer():
219             return "yes"
220         return "no"
221
222     def data_helper_furl(self, ctx, data):
223         try:
224             uploader = self.client.getServiceNamed("uploader")
225         except KeyError:
226             return None
227         furl, connected = uploader.get_helper_info()
228         return furl
229     def data_connected_to_helper(self, ctx, data):
230         try:
231             uploader = self.client.getServiceNamed("uploader")
232         except KeyError:
233             return "no" # we don't even have an Uploader
234         furl, connected = uploader.get_helper_info()
235         if connected:
236             return "yes"
237         return "no"
238
239     def data_known_storage_servers(self, ctx, data):
240         ic = self.client.introducer_client
241         servers = [c
242                    for c in ic.get_all_connectors().values()
243                    if c.service_name == "storage"]
244         return len(servers)
245
246     def data_connected_storage_servers(self, ctx, data):
247         ic = self.client.introducer_client
248         return len(ic.get_all_connections_for("storage"))
249
250     def data_services(self, ctx, data):
251         ic = self.client.introducer_client
252         c = [ (service_name, nodeid, rsc)
253               for (nodeid, service_name), rsc
254               in ic.get_all_connectors().items() ]
255         c.sort()
256         return c
257
258     def render_service_row(self, ctx, data):
259         (service_name, nodeid, rsc) = data
260         ctx.fillSlots("peerid", idlib.nodeid_b2a(nodeid))
261         ctx.fillSlots("nickname", rsc.nickname)
262         if rsc.rref:
263             rhost = rsc.remote_host
264             if nodeid == self.client.nodeid:
265                 rhost_s = "(loopback)"
266             elif isinstance(rhost, address.IPv4Address):
267                 rhost_s = "%s:%d" % (rhost.host, rhost.port)
268             else:
269                 rhost_s = str(rhost)
270             connected = "Yes: to " + rhost_s
271             since = rsc.last_connect_time
272         else:
273             connected = "No"
274             since = rsc.last_loss_time
275
276         TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
277         ctx.fillSlots("connected", connected)
278         ctx.fillSlots("since", time.strftime(TIME_FORMAT, time.localtime(since)))
279         ctx.fillSlots("announced", time.strftime(TIME_FORMAT,
280                                                  time.localtime(rsc.announcement_time)))
281         ctx.fillSlots("version", rsc.version)
282         ctx.fillSlots("service_name", rsc.service_name)
283
284         return ctx.tag
285
286     def render_download_form(self, ctx, data):
287         # this is a form where users can download files by URI
288         form = T.form(action="uri", method="get",
289                       enctype="multipart/form-data")[
290             T.fieldset[
291             T.legend(class_="freeform-form-label")["Download a file"],
292             "URI to download: ",
293             T.input(type="text", name="uri"), " ",
294             "Filename to download as: ",
295             T.input(type="text", name="filename"), " ",
296             T.input(type="submit", value="Download!"),
297             ]]
298         return T.div[form]
299
300     def render_view_form(self, ctx, data):
301         # this is a form where users can download files by URI, or jump to a
302         # named directory
303         form = T.form(action="uri", method="get",
304                       enctype="multipart/form-data")[
305             T.fieldset[
306             T.legend(class_="freeform-form-label")["View a file or directory"],
307             "URI to view: ",
308             T.input(type="text", name="uri"), " ",
309             T.input(type="submit", value="View!"),
310             ]]
311         return T.div[form]
312
313     def render_upload_form(self, ctx, data):
314         # this is a form where users can upload unlinked files
315         form = T.form(action="uri", method="post",
316                       enctype="multipart/form-data")[
317             T.fieldset[
318             T.legend(class_="freeform-form-label")["Upload a file"],
319             "Choose a file: ",
320             T.input(type="file", name="file", class_="freeform-input-file"),
321             T.input(type="hidden", name="t", value="upload"),
322             " Mutable?:", T.input(type="checkbox", name="mutable"),
323             T.input(type="submit", value="Upload!"),
324             ]]
325         return T.div[form]
326
327     def render_mkdir_form(self, ctx, data):
328         # this is a form where users can create new directories
329         form = T.form(action="uri", method="post",
330                       enctype="multipart/form-data")[
331             T.fieldset[
332             T.legend(class_="freeform-form-label")["Create a directory."],
333             T.input(type="hidden", name="t", value="mkdir"),
334             T.input(type="hidden", name="redirect_to_result", value="true"),
335             T.input(type="submit", value="create directory"),
336             ]]
337         return T.div[form]
338
339     def render_incident_button(self, ctx, data):
340         # this button triggers a foolscap-logging "incident"
341         form = T.form(action="report_incident", method="post",
342                       enctype="multipart/form-data")[
343             T.fieldset[
344             T.legend(class_="freeform-form-label")["Report an Incident"],
345             T.input(type="hidden", name="t", value="report-incident"),
346             "What went wrong?: ",
347             T.input(type="text", name="details"), " ",
348             T.input(type="submit", value="Report!"),
349             ]]
350         return T.div[form]