]> arthur.barton.de Git - bup.git/blob - cmd/web-cmd.py
web: fix broken GETs and test
[bup.git] / cmd / web-cmd.py
1 #!/bin/sh
2 """": # -*-python-*-
3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
5 """
6 # end of bup preamble
7
8 from collections import namedtuple
9 import mimetypes, os, posixpath, signal, stat, sys, time, urllib, webbrowser
10
11 from bup import options, git, vfs
12 from bup.helpers import (chunkyreader, debug1, handle_ctrl_c, log,
13                          resource_path, saved_errors)
14
15 try:
16     from tornado import gen
17     from tornado.httpserver import HTTPServer
18     from tornado.ioloop import IOLoop
19     from tornado.netutil import bind_unix_socket
20     import tornado.web
21 except ImportError:
22     log('error: cannot find the python "tornado" module; please install it\n')
23     sys.exit(1)
24
25
26 handle_ctrl_c()
27
28
29 def _compute_breadcrumbs(path, show_hidden=False):
30     """Returns a list of breadcrumb objects for a path."""
31     breadcrumbs = []
32     breadcrumbs.append(('[root]', '/'))
33     path_parts = path.split('/')[1:-1]
34     full_path = '/'
35     for part in path_parts:
36         full_path += part + "/"
37         url_append = ""
38         if show_hidden:
39             url_append = '?hidden=1'
40         breadcrumbs.append((part, full_path+url_append))
41     return breadcrumbs
42
43
44 def _contains_hidden_files(n):
45     """Return True if n contains files starting with a '.', False otherwise."""
46     for sub in n:
47         name = sub.name
48         if len(name)>1 and name.startswith('.'):
49             return True
50
51     return False
52
53
54 def _compute_dir_contents(n, path, show_hidden=False):
55     """Given a vfs node, returns an iterator for display info of all subs."""
56     url_append = ""
57     if show_hidden:
58         url_append = "?hidden=1"
59
60     if path != "/":
61         yield('..', '../' + url_append, '')
62     for sub in n:
63         display = sub.name
64         link = urllib.quote(sub.name)
65
66         # link should be based on fully resolved type to avoid extra
67         # HTTP redirect.
68         if stat.S_ISDIR(sub.try_resolve().mode):
69             link += "/"
70
71         if not show_hidden and len(display)>1 and display.startswith('.'):
72             continue
73
74         size = None
75         if stat.S_ISDIR(sub.mode):
76             display += '/'
77         elif stat.S_ISLNK(sub.mode):
78             display += '@'
79         else:
80             size = sub.size()
81             size = (opt.human_readable and format_filesize(size)) or size
82
83         yield (display, link + url_append, size)
84
85
86 class BupRequestHandler(tornado.web.RequestHandler):
87     def get(self, path):
88         return self._process_request(path)
89
90     def head(self, path):
91         return self._process_request(path)
92     
93     def _process_request(self, path):
94         path = urllib.unquote(path)
95         print 'Handling request for %s' % path
96         try:
97             n = top.resolve(path)
98         except vfs.NoSuchFile:
99             self.send_error(404)
100             return
101         f = None
102         if stat.S_ISDIR(n.mode):
103             self._list_directory(path, n)
104         else:
105             self._get_file(path, n)
106
107     def _list_directory(self, path, n):
108         """Helper to produce a directory listing.
109
110         Return value is either a file object, or None (indicating an
111         error).  In either case, the headers are sent.
112         """
113         if not path.endswith('/') and len(path) > 0:
114             print 'Redirecting from %s to %s' % (path, path + '/')
115             return self.redirect(path + '/', permanent=True)
116
117         try:
118             show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
119         except ValueError as e:
120             show_hidden = False
121
122         self.render(
123             'list-directory.html',
124             path=path,
125             breadcrumbs=_compute_breadcrumbs(path, show_hidden),
126             files_hidden=_contains_hidden_files(n),
127             hidden_shown=show_hidden,
128             dir_contents=_compute_dir_contents(n, path, show_hidden))
129
130     @gen.coroutine
131     def _get_file(self, path, n):
132         """Process a request on a file.
133
134         Return value is either a file object, or None (indicating an error).
135         In either case, the headers are sent.
136         """
137         ctype = self._guess_type(path)
138         self.set_header("Last-Modified", self.date_time_string(n.mtime))
139         self.set_header("Content-Type", ctype)
140         size = n.size()
141         self.set_header("Content-Length", str(size))
142         assert(len(n.hash) == 20)
143         self.set_header("Etag", n.hash.encode('hex'))
144         if self.request.method != 'HEAD':
145             f = n.open()
146             try:
147                 it = chunkyreader(f)
148                 for blob in chunkyreader(f):
149                     self.write(blob)
150             finally:
151                 f.close()
152         raise gen.Return()
153
154     def _guess_type(self, path):
155         """Guess the type of a file.
156
157         Argument is a PATH (a filename).
158
159         Return value is a string of the form type/subtype,
160         usable for a MIME Content-type header.
161
162         The default implementation looks the file's extension
163         up in the table self.extensions_map, using application/octet-stream
164         as a default; however it would be permissible (if
165         slow) to look inside the data to make a better guess.
166         """
167         base, ext = posixpath.splitext(path)
168         if ext in self.extensions_map:
169             return self.extensions_map[ext]
170         ext = ext.lower()
171         if ext in self.extensions_map:
172             return self.extensions_map[ext]
173         else:
174             return self.extensions_map['']
175
176     if not mimetypes.inited:
177         mimetypes.init() # try to read system mime.types
178     extensions_map = mimetypes.types_map.copy()
179     extensions_map.update({
180         '': 'text/plain', # Default
181         '.py': 'text/plain',
182         '.c': 'text/plain',
183         '.h': 'text/plain',
184         })
185
186     def date_time_string(self, t):
187         return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
188
189
190 io_loop = None
191
192 def handle_sigterm(signum, frame):
193     global io_loop
194     debug1('\nbup-web: signal %d received\n' % signum)
195     log('Shutdown requested\n')
196     if not io_loop:
197         sys.exit(0)
198     io_loop.stop()
199
200
201 signal.signal(signal.SIGTERM, handle_sigterm)
202
203 UnixAddress = namedtuple('UnixAddress', ['path'])
204 InetAddress = namedtuple('InetAddress', ['host', 'port'])
205
206 optspec = """
207 bup web [[hostname]:port]
208 bup web unix://path
209 --
210 human-readable    display human readable file sizes (i.e. 3.9K, 4.7M)
211 browser           show repository in default browser (incompatible with unix://)
212 """
213 o = options.Options(optspec)
214 (opt, flags, extra) = o.parse(sys.argv[1:])
215
216 if len(extra) > 1:
217     o.fatal("at most one argument expected")
218
219 if len(extra) == 0:
220     address = InetAddress(host='127.0.0.1', port=8080)
221 else:
222     bind_url = extra[0]
223     if bind_url.startswith('unix://'):
224         address = UnixAddress(path=bind_url[len('unix://'):])
225     else:
226         addr_parts = extra[0].split(':', 1)
227         if len(addr_parts) == 1:
228             host = '127.0.0.1'
229             port = addr_parts[0]
230         else:
231             host, port = addr_parts
232         try:
233             port = int(port)
234         except (TypeError, ValueError) as ex:
235             o.fatal('port must be an integer, not %r', port)
236         address = InetAddress(host=host, port=port)
237
238 git.check_repo_or_die()
239 top = vfs.RefList(None)
240
241 settings = dict(
242     debug = 1,
243     template_path = resource_path('web'),
244     static_path = resource_path('web/static')
245 )
246
247 # Disable buffering on stdout, for debug messages
248 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
249
250 application = tornado.web.Application([
251     (r"(/.*)", BupRequestHandler),
252 ], **settings)
253
254 http_server = HTTPServer(application)
255 io_loop_pending = IOLoop.instance()
256
257 if isinstance(address, InetAddress):
258     http_server.listen(address.port, address.host)
259     try:
260         sock = http_server._socket # tornado < 2.0
261     except AttributeError as e:
262         sock = http_server._sockets.values()[0]
263     print "Serving HTTP on %s:%d..." % sock.getsockname()
264     if opt.browser:
265         browser_addr = 'http://' + address[0] + ':' + str(address[1])
266         io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
267 elif isinstance(address, UnixAddress):
268     unix_socket = bind_unix_socket(address.path)
269     http_server.add_socket(unix_socket)
270     print "Serving HTTP on filesystem socket %r" % address.path
271 else:
272     log('error: unexpected address %r', address)
273     sys.exit(1)
274
275 io_loop = io_loop_pending
276 io_loop.start()
277
278 if saved_errors:
279     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
280     sys.exit(1)