]> arthur.barton.de Git - bup.git/blob - cmd/web-cmd.py
web: retrieve paths exactly as presented
[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
88     def decode_argument(self, value, name=None):
89         if name == 'path':
90             return value
91         return super(BupRequestHandler, self).decode_argument(value, name)
92
93     def get(self, path):
94         return self._process_request(path)
95
96     def head(self, path):
97         return self._process_request(path)
98     
99     def _process_request(self, path):
100         path = urllib.unquote(path)
101         print 'Handling request for %s' % path
102         try:
103             n = top.resolve(path)
104         except vfs.NoSuchFile:
105             self.send_error(404)
106             return
107         f = None
108         if stat.S_ISDIR(n.mode):
109             self._list_directory(path, n)
110         else:
111             self._get_file(path, n)
112
113     def _list_directory(self, path, n):
114         """Helper to produce a directory listing.
115
116         Return value is either a file object, or None (indicating an
117         error).  In either case, the headers are sent.
118         """
119         if not path.endswith('/') and len(path) > 0:
120             print 'Redirecting from %s to %s' % (path, path + '/')
121             return self.redirect(path + '/', permanent=True)
122
123         try:
124             show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
125         except ValueError as e:
126             show_hidden = False
127
128         self.render(
129             'list-directory.html',
130             path=path,
131             breadcrumbs=_compute_breadcrumbs(path, show_hidden),
132             files_hidden=_contains_hidden_files(n),
133             hidden_shown=show_hidden,
134             dir_contents=_compute_dir_contents(n, path, show_hidden))
135
136     @gen.coroutine
137     def _get_file(self, path, n):
138         """Process a request on a file.
139
140         Return value is either a file object, or None (indicating an error).
141         In either case, the headers are sent.
142         """
143         ctype = self._guess_type(path)
144         self.set_header("Last-Modified", self.date_time_string(n.mtime))
145         self.set_header("Content-Type", ctype)
146         size = n.size()
147         self.set_header("Content-Length", str(size))
148         assert(len(n.hash) == 20)
149         self.set_header("Etag", n.hash.encode('hex'))
150         if self.request.method != 'HEAD':
151             f = n.open()
152             try:
153                 it = chunkyreader(f)
154                 for blob in chunkyreader(f):
155                     self.write(blob)
156             finally:
157                 f.close()
158         raise gen.Return()
159
160     def _guess_type(self, path):
161         """Guess the type of a file.
162
163         Argument is a PATH (a filename).
164
165         Return value is a string of the form type/subtype,
166         usable for a MIME Content-type header.
167
168         The default implementation looks the file's extension
169         up in the table self.extensions_map, using application/octet-stream
170         as a default; however it would be permissible (if
171         slow) to look inside the data to make a better guess.
172         """
173         base, ext = posixpath.splitext(path)
174         if ext in self.extensions_map:
175             return self.extensions_map[ext]
176         ext = ext.lower()
177         if ext in self.extensions_map:
178             return self.extensions_map[ext]
179         else:
180             return self.extensions_map['']
181
182     if not mimetypes.inited:
183         mimetypes.init() # try to read system mime.types
184     extensions_map = mimetypes.types_map.copy()
185     extensions_map.update({
186         '': 'text/plain', # Default
187         '.py': 'text/plain',
188         '.c': 'text/plain',
189         '.h': 'text/plain',
190         })
191
192     def date_time_string(self, t):
193         return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
194
195
196 io_loop = None
197
198 def handle_sigterm(signum, frame):
199     global io_loop
200     debug1('\nbup-web: signal %d received\n' % signum)
201     log('Shutdown requested\n')
202     if not io_loop:
203         sys.exit(0)
204     io_loop.stop()
205
206
207 signal.signal(signal.SIGTERM, handle_sigterm)
208
209 UnixAddress = namedtuple('UnixAddress', ['path'])
210 InetAddress = namedtuple('InetAddress', ['host', 'port'])
211
212 optspec = """
213 bup web [[hostname]:port]
214 bup web unix://path
215 --
216 human-readable    display human readable file sizes (i.e. 3.9K, 4.7M)
217 browser           show repository in default browser (incompatible with unix://)
218 """
219 o = options.Options(optspec)
220 (opt, flags, extra) = o.parse(sys.argv[1:])
221
222 if len(extra) > 1:
223     o.fatal("at most one argument expected")
224
225 if len(extra) == 0:
226     address = InetAddress(host='127.0.0.1', port=8080)
227 else:
228     bind_url = extra[0]
229     if bind_url.startswith('unix://'):
230         address = UnixAddress(path=bind_url[len('unix://'):])
231     else:
232         addr_parts = extra[0].split(':', 1)
233         if len(addr_parts) == 1:
234             host = '127.0.0.1'
235             port = addr_parts[0]
236         else:
237             host, port = addr_parts
238         try:
239             port = int(port)
240         except (TypeError, ValueError) as ex:
241             o.fatal('port must be an integer, not %r', port)
242         address = InetAddress(host=host, port=port)
243
244 git.check_repo_or_die()
245 top = vfs.RefList(None)
246
247 settings = dict(
248     debug = 1,
249     template_path = resource_path('web'),
250     static_path = resource_path('web/static')
251 )
252
253 # Disable buffering on stdout, for debug messages
254 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
255
256 application = tornado.web.Application([
257     (r"(?P<path>/.*)", BupRequestHandler),
258 ], **settings)
259
260 http_server = HTTPServer(application)
261 io_loop_pending = IOLoop.instance()
262
263 if isinstance(address, InetAddress):
264     http_server.listen(address.port, address.host)
265     try:
266         sock = http_server._socket # tornado < 2.0
267     except AttributeError as e:
268         sock = http_server._sockets.values()[0]
269     print "Serving HTTP on %s:%d..." % sock.getsockname()
270     if opt.browser:
271         browser_addr = 'http://' + address[0] + ':' + str(address[1])
272         io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
273 elif isinstance(address, UnixAddress):
274     unix_socket = bind_unix_socket(address.path)
275     http_server.add_socket(unix_socket)
276     print "Serving HTTP on filesystem socket %r" % address.path
277 else:
278     log('error: unexpected address %r', address)
279     sys.exit(1)
280
281 io_loop = io_loop_pending
282 io_loop.start()
283
284 if saved_errors:
285     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
286     sys.exit(1)