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, omitsize=False):
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')
77 size = vfs.item_size(repo, item)
78 if opt.human_readable:
79 display_size = format_filesize(size)
86 mode = vfs.item_mode(item)
87 if stat.S_ISDIR(mode):
88 display_name = name + b'/'
90 elif stat.S_ISLNK(mode):
91 display_name = name + b'@'
96 return display_name, link + url_query, display_size
98 dir_item = resolution[-1][1]
99 for name, item in vfs.contents(repo, dir_item):
101 if (name not in (b'.', b'..')) and name.startswith(b'.'):
104 parent_item = resolution[-2][1] if len(resolution) > 1 else dir_item
105 yield display_info(b'..', parent_item, parent_item, b'..', omitsize=True)
107 res_item = vfs.ensure_item_has_metadata(repo, item, include_size=True)
108 yield display_info(name, item, res_item)
111 class BupRequestHandler(tornado.web.RequestHandler):
113 def initialize(self, repo=None):
116 def decode_argument(self, value, name=None):
119 return super(BupRequestHandler, self).decode_argument(value, name)
122 return self._process_request(path)
124 def head(self, path):
125 return self._process_request(path)
127 def _process_request(self, path):
128 print('Handling request for %s' % path)
130 # Set want_meta because dir metadata won't be fetched, and if
131 # it's not a dir, then we're going to want the metadata.
132 res = vfs.resolve(self.repo, path, want_meta=True)
133 leaf_name, leaf_item = res[-1]
137 mode = vfs.item_mode(leaf_item)
138 if stat.S_ISDIR(mode):
139 self._list_directory(path, res)
141 self._get_file(self.repo, path, res)
143 def _list_directory(self, path, resolution):
144 """Helper to produce a directory listing.
146 Return value is either a file object, or None (indicating an
147 error). In either case, the headers are sent.
149 if not path.endswith(b'/') and len(path) > 0:
150 print('Redirecting from %s to %s' % (path_msg(path), path_msg(path + b'/')))
151 return self.redirect(path + b'/', permanent=True)
153 hidden_arg = self.request.arguments.get('hidden', [0])[-1]
155 show_hidden = int(hidden_arg)
156 except ValueError as e:
160 'list-directory.html',
162 breadcrumbs=_compute_breadcrumbs(path, show_hidden),
163 files_hidden=_contains_hidden_files(self.repo, resolution[-1][1]),
164 hidden_shown=show_hidden,
165 dir_contents=_dir_contents(self.repo, resolution,
166 show_hidden=show_hidden))
170 def _get_file(self, repo, path, resolved):
171 """Process a request on a file.
173 Return value is either a file object, or None (indicating an error).
174 In either case, the headers are sent.
176 file_item = resolved[-1][1]
177 file_item = vfs.augment_item_meta(repo, file_item, include_size=True)
178 meta = file_item.meta
179 ctype = self._guess_type(path)
180 self.set_header("Last-Modified", http_date_from_utc_ns(meta.mtime))
181 self.set_header("Content-Type", ctype)
183 self.set_header("Content-Length", str(meta.size))
184 assert len(file_item.oid) == 20
185 self.set_header("Etag", hexlify(file_item.oid))
186 if self.request.method != 'HEAD':
187 with vfs.fopen(self.repo, file_item) as f:
189 for blob in chunkyreader(f):
193 def _guess_type(self, path):
194 """Guess the type of a file.
196 Argument is a PATH (a filename).
198 Return value is a string of the form type/subtype,
199 usable for a MIME Content-type header.
201 The default implementation looks the file's extension
202 up in the table self.extensions_map, using application/octet-stream
203 as a default; however it would be permissible (if
204 slow) to look inside the data to make a better guess.
206 base, ext = posixpath.splitext(path)
207 if ext in self.extensions_map:
208 return self.extensions_map[ext]
210 if ext in self.extensions_map:
211 return self.extensions_map[ext]
213 return self.extensions_map['']
215 if not mimetypes.inited:
216 mimetypes.init() # try to read system mime.types
217 extensions_map = mimetypes.types_map.copy()
218 extensions_map.update({
219 '': 'text/plain', # Default
228 def handle_sigterm(signum, frame):
230 debug1('\nbup-web: signal %d received\n' % signum)
231 log('Shutdown requested\n')
238 bup web [[hostname]:port]
241 human-readable display human readable file sizes (i.e. 3.9K, 4.7M)
242 browser show repository in default browser (incompatible with unix://)
249 signal.signal(signal.SIGTERM, handle_sigterm)
251 UnixAddress = namedtuple('UnixAddress', ['path'])
252 InetAddress = namedtuple('InetAddress', ['host', 'port'])
254 o = options.Options(optspec)
255 opt, flags, extra = o.parse_bytes(argv[1:])
258 o.fatal("at most one argument expected")
261 address = InetAddress(host='127.0.0.1', port=8080)
264 if bind_url.startswith('unix://'):
265 address = UnixAddress(path=bind_url[len('unix://'):])
267 addr_parts = extra[0].split(':', 1)
268 if len(addr_parts) == 1:
272 host, port = addr_parts
275 except (TypeError, ValueError) as ex:
276 o.fatal('port must be an integer, not %r' % port)
277 address = InetAddress(host=host, port=port)
279 git.check_repo_or_die()
283 template_path = resource_path(b'web').decode('utf-8'),
284 static_path = resource_path(b'web/static').decode('utf-8'),
287 # Disable buffering on stdout, for debug messages
289 sys.stdout._line_buffering = True
290 except AttributeError:
291 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
293 with LocalRepo() as repo:
294 handlers = [ (r"(?P<path>/.*)", BupRequestHandler, dict(repo=repo))]
295 application = tornado.web.Application(handlers, **settings)
297 http_server = HTTPServer(application)
298 io_loop_pending = IOLoop.instance()
300 if isinstance(address, InetAddress):
301 sockets = tornado.netutil.bind_sockets(address.port, address.host)
302 http_server.add_sockets(sockets)
303 print('Serving HTTP on %s:%d...' % sockets[0].getsockname()[0:2])
305 browser_addr = 'http://' + address[0] + ':' + str(address[1])
306 io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
307 elif isinstance(address, UnixAddress):
308 unix_socket = bind_unix_socket(address.path)
309 http_server.add_socket(unix_socket)
310 print('Serving HTTP on filesystem socket %r' % address.path)
312 log('error: unexpected address %r', address)
315 io_loop = io_loop_pending
319 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))