2 from __future__ import absolute_import, print_function
3 from collections import namedtuple
4 import mimetypes, os, posixpath, signal, stat, sys, time, webbrowser
5 from binascii import hexlify
8 from bup import options, git, vfs
9 from bup.helpers import (chunkyreader, debug1, format_filesize,
11 from bup.path import resource_path
12 from bup.repo import LocalRepo
13 from bup.io import path_msg
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
22 log('error: cannot find the python "tornado" module; please install it\n')
26 # FIXME: right now the way hidden files are handled causes every
27 # directory to be traversed twice.
30 def http_date_from_utc_ns(utc_ns):
31 return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(utc_ns / 10**9))
34 def _compute_breadcrumbs(path, show_hidden=False):
35 """Returns a list of breadcrumb objects for a path."""
37 breadcrumbs.append((b'[root]', b'/'))
38 path_parts = path.split(b'/')[1:-1]
40 for part in path_parts:
41 full_path += part + b"/"
44 url_append = b'?hidden=1'
45 breadcrumbs.append((part, full_path+url_append))
49 def _contains_hidden_files(repo, dir_item):
50 """Return true if the directory contains items with names other than
51 '.' and '..' that begin with '.'
54 for name, item in vfs.contents(repo, dir_item, want_meta=False):
55 if name in (b'.', b'..'):
57 if name.startswith(b'.'):
62 def _dir_contents(repo, resolution, show_hidden=False):
63 """Yield the display information for the contents of dir_item."""
65 url_query = b'?hidden=1' if show_hidden else b''
67 def display_info(name, item, resolved_item, display_name=None):
69 # link should be based on fully resolved type to avoid extra
71 link = tornado.escape.url_escape(name, plus=False)
72 if stat.S_ISDIR(vfs.item_mode(resolved_item)):
74 link = link.encode('ascii')
76 size = vfs.item_size(repo, item)
77 if opt.human_readable:
78 display_size = format_filesize(size)
83 mode = vfs.item_mode(item)
84 if stat.S_ISDIR(mode):
85 display_name = name + b'/'
86 elif stat.S_ISLNK(mode):
87 display_name = name + b'@'
91 return display_name, link + url_query, display_size
93 dir_item = resolution[-1][1]
94 for name, item in vfs.contents(repo, dir_item):
96 if (name not in (b'.', b'..')) and name.startswith(b'.'):
99 parent_item = resolution[-2][1] if len(resolution) > 1 else dir_item
100 yield display_info(b'..', parent_item, parent_item, b'..')
102 res_item = vfs.ensure_item_has_metadata(repo, item, include_size=True)
103 yield display_info(name, item, res_item)
106 class BupRequestHandler(tornado.web.RequestHandler):
108 def initialize(self, repo=None):
111 def decode_argument(self, value, name=None):
114 return super(BupRequestHandler, self).decode_argument(value, name)
117 return self._process_request(path)
119 def head(self, path):
120 return self._process_request(path)
122 def _process_request(self, path):
123 print('Handling request for %s' % path)
125 # Set want_meta because dir metadata won't be fetched, and if
126 # it's not a dir, then we're going to want the metadata.
127 res = vfs.resolve(self.repo, path, want_meta=True)
128 leaf_name, leaf_item = res[-1]
132 mode = vfs.item_mode(leaf_item)
133 if stat.S_ISDIR(mode):
134 self._list_directory(path, res)
136 self._get_file(self.repo, path, res)
138 def _list_directory(self, path, resolution):
139 """Helper to produce a directory listing.
141 Return value is either a file object, or None (indicating an
142 error). In either case, the headers are sent.
144 if not path.endswith(b'/') and len(path) > 0:
145 print('Redirecting from %s to %s' % (path_msg(path), path_msg(path + b'/')))
146 return self.redirect(path + b'/', permanent=True)
148 hidden_arg = self.request.arguments.get('hidden', [0])[-1]
150 show_hidden = int(hidden_arg)
151 except ValueError as e:
155 'list-directory.html',
157 breadcrumbs=_compute_breadcrumbs(path, show_hidden),
158 files_hidden=_contains_hidden_files(self.repo, resolution[-1][1]),
159 hidden_shown=show_hidden,
160 dir_contents=_dir_contents(self.repo, resolution,
161 show_hidden=show_hidden))
164 def _get_file(self, repo, path, resolved):
165 """Process a request on a file.
167 Return value is either a file object, or None (indicating an error).
168 In either case, the headers are sent.
170 file_item = resolved[-1][1]
171 file_item = vfs.augment_item_meta(repo, file_item, include_size=True)
172 meta = file_item.meta
173 ctype = self._guess_type(path)
174 self.set_header("Last-Modified", http_date_from_utc_ns(meta.mtime))
175 self.set_header("Content-Type", ctype)
177 self.set_header("Content-Length", str(meta.size))
178 assert len(file_item.oid) == 20
179 self.set_header("Etag", hexlify(file_item.oid))
180 if self.request.method != 'HEAD':
181 with vfs.fopen(self.repo, file_item) as f:
183 for blob in chunkyreader(f):
187 def _guess_type(self, path):
188 """Guess the type of a file.
190 Argument is a PATH (a filename).
192 Return value is a string of the form type/subtype,
193 usable for a MIME Content-type header.
195 The default implementation looks the file's extension
196 up in the table self.extensions_map, using application/octet-stream
197 as a default; however it would be permissible (if
198 slow) to look inside the data to make a better guess.
200 base, ext = posixpath.splitext(path)
201 if ext in self.extensions_map:
202 return self.extensions_map[ext]
204 if ext in self.extensions_map:
205 return self.extensions_map[ext]
207 return self.extensions_map['']
209 if not mimetypes.inited:
210 mimetypes.init() # try to read system mime.types
211 extensions_map = mimetypes.types_map.copy()
212 extensions_map.update({
213 '': 'text/plain', # Default
222 def handle_sigterm(signum, frame):
224 debug1('\nbup-web: signal %d received\n' % signum)
225 log('Shutdown requested\n')
232 bup web [[hostname]:port]
235 human-readable display human readable file sizes (i.e. 3.9K, 4.7M)
236 browser show repository in default browser (incompatible with unix://)
243 signal.signal(signal.SIGTERM, handle_sigterm)
245 UnixAddress = namedtuple('UnixAddress', ['path'])
246 InetAddress = namedtuple('InetAddress', ['host', 'port'])
248 o = options.Options(optspec)
249 opt, flags, extra = o.parse_bytes(argv[1:])
252 o.fatal("at most one argument expected")
255 address = InetAddress(host='127.0.0.1', port=8080)
258 if bind_url.startswith('unix://'):
259 address = UnixAddress(path=bind_url[len('unix://'):])
261 addr_parts = extra[0].split(':', 1)
262 if len(addr_parts) == 1:
266 host, port = addr_parts
269 except (TypeError, ValueError) as ex:
270 o.fatal('port must be an integer, not %r' % port)
271 address = InetAddress(host=host, port=port)
273 git.check_repo_or_die()
277 template_path = resource_path(b'web').decode('utf-8'),
278 static_path = resource_path(b'web/static').decode('utf-8'),
281 # Disable buffering on stdout, for debug messages
283 sys.stdout._line_buffering = True
284 except AttributeError:
285 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
287 application = tornado.web.Application([
288 (r"(?P<path>/.*)", BupRequestHandler, dict(repo=LocalRepo())),
291 http_server = HTTPServer(application)
292 io_loop_pending = IOLoop.instance()
294 if isinstance(address, InetAddress):
295 sockets = tornado.netutil.bind_sockets(address.port, address.host)
296 http_server.add_sockets(sockets)
297 print('Serving HTTP on %s:%d...' % sockets[0].getsockname()[0:2])
299 browser_addr = 'http://' + address[0] + ':' + str(address[1])
300 io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
301 elif isinstance(address, UnixAddress):
302 unix_socket = bind_unix_socket(address.path)
303 http_server.add_socket(unix_socket)
304 print('Serving HTTP on filesystem socket %r' % address.path)
306 log('error: unexpected address %r', address)
309 io_loop = io_loop_pending
313 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))