]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/webish.py
webish: complete rewrite, break into smaller pieces, auto-create directories, improve...
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / webish.py
1
2 from twisted.application import service, strports, internet
3 from twisted.web import http
4 from twisted.internet import defer
5 from nevow import appserver, inevow
6 from allmydata.util import log
7
8 from allmydata.web import introweb, root
9 from allmydata.web.common import IClient, MyExceptionHandler
10
11 # we must override twisted.web.http.Request.requestReceived with a version
12 # that doesn't use cgi.parse_multipart() . Since we actually use Nevow, we
13 # override the nevow-specific subclass, nevow.appserver.NevowRequest . This
14 # is an exact copy of twisted.web.http.Request (from SVN HEAD on 10-Aug-2007)
15 # that modifies the way form arguments are parsed. Note that this sort of
16 # surgery may induce a dependency upon a particular version of twisted.web
17
18 parse_qs = http.parse_qs
19 class MyRequest(appserver.NevowRequest):
20     fields = None
21     def requestReceived(self, command, path, version):
22         """Called by channel when all data has been received.
23
24         This method is not intended for users.
25         """
26         self.content.seek(0,0)
27         self.args = {}
28         self.stack = []
29
30         self.method, self.uri = command, path
31         self.clientproto = version
32         x = self.uri.split('?', 1)
33
34         if len(x) == 1:
35             self.path = self.uri
36         else:
37             self.path, argstring = x
38             self.args = parse_qs(argstring, 1)
39
40         # cache the client and server information, we'll need this later to be
41         # serialized and sent with the request so CGIs will work remotely
42         self.client = self.channel.transport.getPeer()
43         self.host = self.channel.transport.getHost()
44
45         # Argument processing.
46
47 ##      The original twisted.web.http.Request.requestReceived code parsed the
48 ##      content and added the form fields it found there to self.args . It
49 ##      did this with cgi.parse_multipart, which holds the arguments in RAM
50 ##      and is thus unsuitable for large file uploads. The Nevow subclass
51 ##      (nevow.appserver.NevowRequest) uses cgi.FieldStorage instead (putting
52 ##      the results in self.fields), which is much more memory-efficient.
53 ##      Since we know we're using Nevow, we can anticipate these arguments
54 ##      appearing in self.fields instead of self.args, and thus skip the
55 ##      parse-content-into-self.args step.
56
57 ##      args = self.args
58 ##      ctype = self.getHeader('content-type')
59 ##      if self.method == "POST" and ctype:
60 ##          mfd = 'multipart/form-data'
61 ##          key, pdict = cgi.parse_header(ctype)
62 ##          if key == 'application/x-www-form-urlencoded':
63 ##              args.update(parse_qs(self.content.read(), 1))
64 ##          elif key == mfd:
65 ##              try:
66 ##                  args.update(cgi.parse_multipart(self.content, pdict))
67 ##              except KeyError, e:
68 ##                  if e.args[0] == 'content-disposition':
69 ##                      # Parse_multipart can't cope with missing
70 ##                      # content-dispostion headers in multipart/form-data
71 ##                      # parts, so we catch the exception and tell the client
72 ##                      # it was a bad request.
73 ##                      self.channel.transport.write(
74 ##                              "HTTP/1.1 400 Bad Request\r\n\r\n")
75 ##                      self.channel.transport.loseConnection()
76 ##                      return
77 ##                  raise
78         self.process()
79
80     def _logger(self):
81         # we build up a log string that hides most of the cap, to preserve
82         # user privacy. We retain the query args so we can identify things
83         # like t=json. Then we send it to the flog. We make no attempt to
84         # match apache formatting. TODO: when we move to DSA dirnodes and
85         # shorter caps, consider exposing a few characters of the cap, or
86         # maybe a few characters of its hash.
87         x = self.uri.split("?", 1)
88         if len(x) == 1:
89             # no query args
90             path = self.uri
91             queryargs = ""
92         else:
93             path, queryargs = x
94             # there is a form handler which redirects POST /uri?uri=FOO into
95             # GET /uri/FOO so folks can paste in non-HTTP-prefixed uris. Make
96             # sure we censor these too.
97             if queryargs.startswith("uri="):
98                 queryargs = "[uri=CENSORED]"
99             queryargs = "?" + queryargs
100         if path.startswith("/uri"):
101             path = "/uri/[CENSORED].."
102         uri = path + queryargs
103
104         log.msg(format="web: %(clientip)s %(method)s %(uri)s %(code)s %(length)s",
105                 clientip=self.getClientIP(),
106                 method=self.method,
107                 uri=uri,
108                 code=self.code,
109                 length=(self.sentLength or "-"),
110                 facility="tahoe.webish",
111                 level=log.OPERATIONAL,
112                 )
113
114
115
116 class WebishServer(service.MultiService):
117     name = "webish"
118     root_class = root.Root
119
120     def __init__(self, webport, nodeurl_path=None):
121         service.MultiService.__init__(self)
122         self.webport = webport
123         self.root = self.root_class()
124         self.site = site = appserver.NevowSite(self.root)
125         self.site.requestFactory = MyRequest
126         s = strports.service(webport, site)
127         s.setServiceParent(self)
128         self.listener = s # stash it so the tests can query for the portnum
129         self._started = defer.Deferred()
130         if nodeurl_path:
131             self._started.addCallback(self._write_nodeurl_file, nodeurl_path)
132
133     def startService(self):
134         service.MultiService.startService(self)
135         # to make various services available to render_* methods, we stash a
136         # reference to the client on the NevowSite. This will be available by
137         # adapting the 'context' argument to a special marker interface named
138         # IClient.
139         self.site.remember(self.parent, IClient)
140         # I thought you could do the same with an existing interface, but
141         # apparently 'ISite' does not exist
142         #self.site._client = self.parent
143         self.site.remember(MyExceptionHandler(), inevow.ICanHandleException)
144         self._started.callback(None)
145
146     def _write_nodeurl_file(self, junk, nodeurl_path):
147         # what is our webport?
148         s = self.listener
149         if isinstance(s, internet.TCPServer):
150             base_url = "http://127.0.0.1:%d/" % s._port.getHost().port
151         elif isinstance(s, internet.SSLServer):
152             base_url = "https://127.0.0.1:%d/" % s._port.getHost().port
153         else:
154             base_url = None
155         if base_url:
156             f = open(nodeurl_path, 'wb')
157             # this file is world-readable
158             f.write(base_url + "\n")
159             f.close()
160
161 class IntroducerWebishServer(WebishServer):
162     root_class = introweb.IntroducerRoot