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