3 # https://sourceware.org/bugzilla/show_bug.cgi?id=26034
4 export "BUP_ARGV_0"="$0"
7 export "BUP_ARGV_${arg_i}"="$arg"
11 # Here to end of preamble replaced during install
12 bup_python="$(dirname "$0")/../../config/bin/python" || exit $?
13 exec "$bup_python" "$0"
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
22 sys.path[:0] = [os.path.dirname(os.path.realpath(__file__)) + '/..']
24 from bup import compat, options, git, vfs
25 from bup.helpers import (chunkyreader, debug1, format_filesize, handle_ctrl_c,
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
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
39 log('error: cannot find the python "tornado" module; please install it\n')
43 # FIXME: right now the way hidden files are handled causes every
44 # directory to be traversed twice.
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))
53 def _compute_breadcrumbs(path, show_hidden=False):
54 """Returns a list of breadcrumb objects for a path."""
56 breadcrumbs.append((b'[root]', b'/'))
57 path_parts = path.split(b'/')[1:-1]
59 for part in path_parts:
60 full_path += part + b"/"
63 url_append = b'?hidden=1'
64 breadcrumbs.append((part, full_path+url_append))
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 '.'
73 for name, item in vfs.contents(repo, dir_item, want_meta=False):
74 if name in (b'.', b'..'):
76 if name.startswith(b'.'):
81 def _dir_contents(repo, resolution, show_hidden=False):
82 """Yield the display information for the contents of dir_item."""
84 url_query = b'?hidden=1' if show_hidden else b''
86 def display_info(name, item, resolved_item, display_name=None):
87 # link should be based on fully resolved type to avoid extra
89 link = tornado.escape.url_escape(name, plus=False)
90 if stat.S_ISDIR(vfs.item_mode(resolved_item)):
92 link = link.encode('ascii')
94 size = vfs.item_size(repo, item)
95 if opt.human_readable:
96 display_size = format_filesize(size)
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'@'
109 return display_name, link + url_query, display_size
111 dir_item = resolution[-1][1]
112 for name, item in vfs.contents(repo, dir_item):
114 if (name not in (b'.', b'..')) and name.startswith(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'..')
121 res_item = vfs.ensure_item_has_metadata(repo, item, include_size=True)
122 yield display_info(name, item, res_item)
125 class BupRequestHandler(tornado.web.RequestHandler):
127 def initialize(self, repo=None):
130 def decode_argument(self, value, name=None):
133 return super(BupRequestHandler, self).decode_argument(value, name)
136 return self._process_request(path)
138 def head(self, path):
139 return self._process_request(path)
141 def _process_request(self, path):
142 print('Handling request for %s' % path)
144 # Set want_meta because dir metadata won't be fetched, and if
145 # it's not a dir, then we're going to want the metadata.
146 res = vfs.resolve(self.repo, path, want_meta=True)
147 leaf_name, leaf_item = res[-1]
151 mode = vfs.item_mode(leaf_item)
152 if stat.S_ISDIR(mode):
153 self._list_directory(path, res)
155 self._get_file(self.repo, path, res)
157 def _list_directory(self, path, resolution):
158 """Helper to produce a directory listing.
160 Return value is either a file object, or None (indicating an
161 error). In either case, the headers are sent.
163 if not path.endswith(b'/') and len(path) > 0:
164 print('Redirecting from %s to %s' % (path_msg(path), path_msg(path + b'/')))
165 return self.redirect(path + b'/', permanent=True)
167 hidden_arg = self.request.arguments.get('hidden', [0])[-1]
169 show_hidden = int(hidden_arg)
170 except ValueError as e:
174 'list-directory.html',
176 breadcrumbs=_compute_breadcrumbs(path, show_hidden),
177 files_hidden=_contains_hidden_files(self.repo, resolution[-1][1]),
178 hidden_shown=show_hidden,
179 dir_contents=_dir_contents(self.repo, resolution,
180 show_hidden=show_hidden))
183 def _get_file(self, repo, path, resolved):
184 """Process a request on a file.
186 Return value is either a file object, or None (indicating an error).
187 In either case, the headers are sent.
189 file_item = resolved[-1][1]
190 file_item = vfs.augment_item_meta(repo, file_item, include_size=True)
191 meta = file_item.meta
192 ctype = self._guess_type(path)
193 self.set_header("Last-Modified", http_date_from_utc_ns(meta.mtime))
194 self.set_header("Content-Type", ctype)
196 self.set_header("Content-Length", str(meta.size))
197 assert len(file_item.oid) == 20
198 self.set_header("Etag", hexlify(file_item.oid))
199 if self.request.method != 'HEAD':
200 with vfs.fopen(self.repo, file_item) as f:
202 for blob in chunkyreader(f):
206 def _guess_type(self, path):
207 """Guess the type of a file.
209 Argument is a PATH (a filename).
211 Return value is a string of the form type/subtype,
212 usable for a MIME Content-type header.
214 The default implementation looks the file's extension
215 up in the table self.extensions_map, using application/octet-stream
216 as a default; however it would be permissible (if
217 slow) to look inside the data to make a better guess.
219 base, ext = posixpath.splitext(path)
220 if ext in self.extensions_map:
221 return self.extensions_map[ext]
223 if ext in self.extensions_map:
224 return self.extensions_map[ext]
226 return self.extensions_map['']
228 if not mimetypes.inited:
229 mimetypes.init() # try to read system mime.types
230 extensions_map = mimetypes.types_map.copy()
231 extensions_map.update({
232 '': 'text/plain', # Default
241 def handle_sigterm(signum, frame):
243 debug1('\nbup-web: signal %d received\n' % signum)
244 log('Shutdown requested\n')
250 signal.signal(signal.SIGTERM, handle_sigterm)
252 UnixAddress = namedtuple('UnixAddress', ['path'])
253 InetAddress = namedtuple('InetAddress', ['host', 'port'])
256 bup web [[hostname]:port]
259 human-readable display human readable file sizes (i.e. 3.9K, 4.7M)
260 browser show repository in default browser (incompatible with unix://)
262 o = options.Options(optspec)
263 opt, flags, extra = o.parse(compat.argv[1:])
266 o.fatal("at most one argument expected")
269 address = InetAddress(host='127.0.0.1', port=8080)
272 if bind_url.startswith('unix://'):
273 address = UnixAddress(path=bind_url[len('unix://'):])
275 addr_parts = extra[0].split(':', 1)
276 if len(addr_parts) == 1:
280 host, port = addr_parts
283 except (TypeError, ValueError) as ex:
284 o.fatal('port must be an integer, not %r' % port)
285 address = InetAddress(host=host, port=port)
287 git.check_repo_or_die()
291 template_path = resource_path(b'web').decode('utf-8'),
292 static_path = resource_path(b'web/static').decode('utf-8'),
295 # Disable buffering on stdout, for debug messages
297 sys.stdout._line_buffering = True
298 except AttributeError:
299 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
301 application = tornado.web.Application([
302 (r"(?P<path>/.*)", BupRequestHandler, dict(repo=LocalRepo())),
305 http_server = HTTPServer(application)
306 io_loop_pending = IOLoop.instance()
308 if isinstance(address, InetAddress):
309 sockets = tornado.netutil.bind_sockets(address.port, address.host)
310 http_server.add_sockets(sockets)
311 print('Serving HTTP on %s:%d...' % sockets[0].getsockname())
313 browser_addr = 'http://' + address[0] + ':' + str(address[1])
314 io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
315 elif isinstance(address, UnixAddress):
316 unix_socket = bind_unix_socket(address.path)
317 http_server.add_socket(unix_socket)
318 print('Serving HTTP on filesystem socket %r' % address.path)
320 log('error: unexpected address %r', address)
323 io_loop = io_loop_pending
327 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))