]> arthur.barton.de Git - bup.git/blob - lib/cmd/web-cmd.py
d765463d854df9a5218273e0d53def45c0f47d8b
[bup.git] / lib / cmd / web-cmd.py
1 #!/bin/sh
2 """": # -*-python-*-
3 # https://sourceware.org/bugzilla/show_bug.cgi?id=26034
4 export "BUP_ARGV_0"="$0"
5 arg_i=1
6 for arg in "$@"; do
7     export "BUP_ARGV_${arg_i}"="$arg"
8     shift
9     arg_i=$((arg_i + 1))
10 done
11 # Here to end of preamble replaced during install
12 bup_python="$(dirname "$0")/../../config/bin/python" || exit $?
13 exec "$bup_python" "$0"
14 """
15 # end of bup preamble
16
17 from __future__ import absolute_import, print_function
18 from collections import namedtuple
19 import mimetypes, os, posixpath, signal, stat, sys, time, urllib, webbrowser
20 from binascii import hexlify
21
22 sys.path[:0] = [os.path.dirname(os.path.realpath(__file__)) + '/..']
23
24 from bup import compat, options, git, vfs
25 from bup.helpers import (chunkyreader, debug1, format_filesize, handle_ctrl_c,
26                          log, saved_errors)
27 from bup.metadata import Metadata
28 from bup.path import resource_path
29 from bup.repo import LocalRepo
30 from bup.io import path_msg
31
32 try:
33     from tornado import gen
34     from tornado.httpserver import HTTPServer
35     from tornado.ioloop import IOLoop
36     from tornado.netutil import bind_unix_socket
37     import tornado.web
38 except ImportError:
39     log('error: cannot find the python "tornado" module; please install it\n')
40     sys.exit(1)
41
42
43 # FIXME: right now the way hidden files are handled causes every
44 # directory to be traversed twice.
45
46 handle_ctrl_c()
47
48
49 def http_date_from_utc_ns(utc_ns):
50     return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(utc_ns / 10**9))
51
52
53 def _compute_breadcrumbs(path, show_hidden=False):
54     """Returns a list of breadcrumb objects for a path."""
55     breadcrumbs = []
56     breadcrumbs.append((b'[root]', b'/'))
57     path_parts = path.split(b'/')[1:-1]
58     full_path = b'/'
59     for part in path_parts:
60         full_path += part + b"/"
61         url_append = b""
62         if show_hidden:
63             url_append = b'?hidden=1'
64         breadcrumbs.append((part, full_path+url_append))
65     return breadcrumbs
66
67
68 def _contains_hidden_files(repo, dir_item):
69     """Return true if the directory contains items with names other than
70     '.' and '..' that begin with '.'
71
72     """
73     for name, item in vfs.contents(repo, dir_item, want_meta=False):
74         if name in (b'.', b'..'):
75             continue
76         if name.startswith(b'.'):
77             return True
78     return False
79
80
81 def _dir_contents(repo, resolution, show_hidden=False):
82     """Yield the display information for the contents of dir_item."""
83
84     url_query = b'?hidden=1' if show_hidden else b''
85
86     def display_info(name, item, resolved_item, display_name=None):
87         # link should be based on fully resolved type to avoid extra
88         # HTTP redirect.
89         link = tornado.escape.url_escape(name, plus=False)
90         if stat.S_ISDIR(vfs.item_mode(resolved_item)):
91             link += '/'
92         link = link.encode('ascii')
93
94         size = vfs.item_size(repo, item)
95         if opt.human_readable:
96             display_size = format_filesize(size)
97         else:
98             display_size = size
99
100         if not display_name:
101             mode = vfs.item_mode(item)
102             if stat.S_ISDIR(mode):
103                 display_name = name + b'/'
104             elif stat.S_ISLNK(mode):
105                 display_name = name + b'@'
106             else:
107                 display_name = name
108
109         return display_name, link + url_query, display_size
110
111     dir_item = resolution[-1][1]    
112     for name, item in vfs.contents(repo, dir_item):
113         if not show_hidden:
114             if (name not in (b'.', b'..')) and name.startswith(b'.'):
115                 continue
116         if name == b'.':
117             yield display_info(name, item, item, b'.')
118             parent_item = resolution[-2][1] if len(resolution) > 1 else dir_item
119             yield display_info(b'..', parent_item, parent_item, b'..')
120             continue
121         res = vfs.try_resolve(repo, name, parent=resolution, want_meta=False)
122         res_name, res_item = res[-1]
123         yield display_info(name, item, res_item)
124
125
126 class BupRequestHandler(tornado.web.RequestHandler):
127
128     def initialize(self, repo=None):
129         self.repo = repo
130
131     def decode_argument(self, value, name=None):
132         if name == 'path':
133             return value
134         return super(BupRequestHandler, self).decode_argument(value, name)
135
136     def get(self, path):
137         return self._process_request(path)
138
139     def head(self, path):
140         return self._process_request(path)
141     
142     def _process_request(self, path):
143         print('Handling request for %s' % path)
144         sys.stdout.flush()
145         # Set want_meta because dir metadata won't be fetched, and if
146         # it's not a dir, then we're going to want the metadata.
147         res = vfs.resolve(self.repo, path, want_meta=True)
148         leaf_name, leaf_item = res[-1]
149         if not leaf_item:
150             self.send_error(404)
151             return
152         mode = vfs.item_mode(leaf_item)
153         if stat.S_ISDIR(mode):
154             self._list_directory(path, res)
155         else:
156             self._get_file(self.repo, path, res)
157
158     def _list_directory(self, path, resolution):
159         """Helper to produce a directory listing.
160
161         Return value is either a file object, or None (indicating an
162         error).  In either case, the headers are sent.
163         """
164         if not path.endswith(b'/') and len(path) > 0:
165             print('Redirecting from %s to %s' % (path_msg(path), path_msg(path + b'/')))
166             return self.redirect(path + b'/', permanent=True)
167
168         hidden_arg = self.request.arguments.get('hidden', [0])[-1]
169         try:
170             show_hidden = int(hidden_arg)
171         except ValueError as e:
172             show_hidden = False
173
174         self.render(
175             'list-directory.html',
176             path=path,
177             breadcrumbs=_compute_breadcrumbs(path, show_hidden),
178             files_hidden=_contains_hidden_files(self.repo, resolution[-1][1]),
179             hidden_shown=show_hidden,
180             dir_contents=_dir_contents(self.repo, resolution,
181                                        show_hidden=show_hidden))
182
183     @gen.coroutine
184     def _get_file(self, repo, path, resolved):
185         """Process a request on a file.
186
187         Return value is either a file object, or None (indicating an error).
188         In either case, the headers are sent.
189         """
190         file_item = resolved[-1][1]
191         file_item = vfs.augment_item_meta(repo, file_item, include_size=True)
192         meta = file_item.meta
193         ctype = self._guess_type(path)
194         self.set_header("Last-Modified", http_date_from_utc_ns(meta.mtime))
195         self.set_header("Content-Type", ctype)
196         
197         self.set_header("Content-Length", str(meta.size))
198         assert len(file_item.oid) == 20
199         self.set_header("Etag", hexlify(file_item.oid))
200         if self.request.method != 'HEAD':
201             with vfs.fopen(self.repo, file_item) as f:
202                 it = chunkyreader(f)
203                 for blob in chunkyreader(f):
204                     self.write(blob)
205         raise gen.Return()
206
207     def _guess_type(self, path):
208         """Guess the type of a file.
209
210         Argument is a PATH (a filename).
211
212         Return value is a string of the form type/subtype,
213         usable for a MIME Content-type header.
214
215         The default implementation looks the file's extension
216         up in the table self.extensions_map, using application/octet-stream
217         as a default; however it would be permissible (if
218         slow) to look inside the data to make a better guess.
219         """
220         base, ext = posixpath.splitext(path)
221         if ext in self.extensions_map:
222             return self.extensions_map[ext]
223         ext = ext.lower()
224         if ext in self.extensions_map:
225             return self.extensions_map[ext]
226         else:
227             return self.extensions_map['']
228
229     if not mimetypes.inited:
230         mimetypes.init() # try to read system mime.types
231     extensions_map = mimetypes.types_map.copy()
232     extensions_map.update({
233         '': 'text/plain', # Default
234         '.py': 'text/plain',
235         '.c': 'text/plain',
236         '.h': 'text/plain',
237         })
238
239
240 io_loop = None
241
242 def handle_sigterm(signum, frame):
243     global io_loop
244     debug1('\nbup-web: signal %d received\n' % signum)
245     log('Shutdown requested\n')
246     if not io_loop:
247         sys.exit(0)
248     io_loop.stop()
249
250
251 signal.signal(signal.SIGTERM, handle_sigterm)
252
253 UnixAddress = namedtuple('UnixAddress', ['path'])
254 InetAddress = namedtuple('InetAddress', ['host', 'port'])
255
256 optspec = """
257 bup web [[hostname]:port]
258 bup web unix://path
259 --
260 human-readable    display human readable file sizes (i.e. 3.9K, 4.7M)
261 browser           show repository in default browser (incompatible with unix://)
262 """
263 o = options.Options(optspec)
264 opt, flags, extra = o.parse(compat.argv[1:])
265
266 if len(extra) > 1:
267     o.fatal("at most one argument expected")
268
269 if len(extra) == 0:
270     address = InetAddress(host='127.0.0.1', port=8080)
271 else:
272     bind_url = extra[0]
273     if bind_url.startswith('unix://'):
274         address = UnixAddress(path=bind_url[len('unix://'):])
275     else:
276         addr_parts = extra[0].split(':', 1)
277         if len(addr_parts) == 1:
278             host = '127.0.0.1'
279             port = addr_parts[0]
280         else:
281             host, port = addr_parts
282         try:
283             port = int(port)
284         except (TypeError, ValueError) as ex:
285             o.fatal('port must be an integer, not %r' % port)
286         address = InetAddress(host=host, port=port)
287
288 git.check_repo_or_die()
289
290 settings = dict(
291     debug = 1,
292     template_path = resource_path(b'web').decode('utf-8'),
293     static_path = resource_path(b'web/static').decode('utf-8'),
294 )
295
296 # Disable buffering on stdout, for debug messages
297 try:
298     sys.stdout._line_buffering = True
299 except AttributeError:
300     sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
301
302 application = tornado.web.Application([
303     (r"(?P<path>/.*)", BupRequestHandler, dict(repo=LocalRepo())),
304 ], **settings)
305
306 http_server = HTTPServer(application)
307 io_loop_pending = IOLoop.instance()
308
309 if isinstance(address, InetAddress):
310     sockets = tornado.netutil.bind_sockets(address.port, address.host)
311     http_server.add_sockets(sockets)
312     print('Serving HTTP on %s:%d...' % sockets[0].getsockname())
313     if opt.browser:
314         browser_addr = 'http://' + address[0] + ':' + str(address[1])
315         io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
316 elif isinstance(address, UnixAddress):
317     unix_socket = bind_unix_socket(address.path)
318     http_server.add_socket(unix_socket)
319     print('Serving HTTP on filesystem socket %r' % address.path)
320 else:
321     log('error: unexpected address %r', address)
322     sys.exit(1)
323
324 io_loop = io_loop_pending
325 io_loop.start()
326
327 if saved_errors:
328     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
329     sys.exit(1)