3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
8 from collections import namedtuple
9 import mimetypes, os, posixpath, signal, stat, sys, time, urllib, webbrowser
11 from bup import options, git, vfs
12 from bup.helpers import (chunkyreader, debug1, handle_ctrl_c, log,
13 resource_path, saved_errors)
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')
29 def _compute_breadcrumbs(path, show_hidden=False):
30 """Returns a list of breadcrumb objects for a path."""
32 breadcrumbs.append(('[root]', '/'))
33 path_parts = path.split('/')[1:-1]
35 for part in path_parts:
36 full_path += part + "/"
39 url_append = '?hidden=1'
40 breadcrumbs.append((part, full_path+url_append))
44 def _contains_hidden_files(n):
45 """Return True if n contains files starting with a '.', False otherwise."""
48 if len(name)>1 and name.startswith('.'):
54 def _compute_dir_contents(n, path, show_hidden=False):
55 """Given a vfs node, returns an iterator for display info of all subs."""
58 url_append = "?hidden=1"
61 yield('..', '../' + url_append, '')
64 link = urllib.quote(sub.name)
66 # link should be based on fully resolved type to avoid extra
68 if stat.S_ISDIR(sub.try_resolve().mode):
71 if not show_hidden and len(display)>1 and display.startswith('.'):
75 if stat.S_ISDIR(sub.mode):
77 elif stat.S_ISLNK(sub.mode):
81 size = (opt.human_readable and format_filesize(size)) or size
83 yield (display, link + url_append, size)
86 class BupRequestHandler(tornado.web.RequestHandler):
88 return self._process_request(path)
91 return self._process_request(path)
93 def _process_request(self, path):
94 path = urllib.unquote(path)
95 print 'Handling request for %s' % path
98 except vfs.NoSuchFile:
102 if stat.S_ISDIR(n.mode):
103 self._list_directory(path, n)
105 self._get_file(path, n)
107 def _list_directory(self, path, n):
108 """Helper to produce a directory listing.
110 Return value is either a file object, or None (indicating an
111 error). In either case, the headers are sent.
113 if not path.endswith('/') and len(path) > 0:
114 print 'Redirecting from %s to %s' % (path, path + '/')
115 return self.redirect(path + '/', permanent=True)
118 show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
119 except ValueError as e:
123 'list-directory.html',
125 breadcrumbs=_compute_breadcrumbs(path, show_hidden),
126 files_hidden=_contains_hidden_files(n),
127 hidden_shown=show_hidden,
128 dir_contents=_compute_dir_contents(n, path, show_hidden))
131 def _get_file(self, path, n):
132 """Process a request on a file.
134 Return value is either a file object, or None (indicating an error).
135 In either case, the headers are sent.
137 ctype = self._guess_type(path)
138 self.set_header("Last-Modified", self.date_time_string(n.mtime))
139 self.set_header("Content-Type", ctype)
141 self.set_header("Content-Length", str(size))
142 assert(len(n.hash) == 20)
143 self.set_header("Etag", n.hash.encode('hex'))
144 if self.request.method != 'HEAD':
148 for blob in chunkyreader(f):
154 def _guess_type(self, path):
155 """Guess the type of a file.
157 Argument is a PATH (a filename).
159 Return value is a string of the form type/subtype,
160 usable for a MIME Content-type header.
162 The default implementation looks the file's extension
163 up in the table self.extensions_map, using application/octet-stream
164 as a default; however it would be permissible (if
165 slow) to look inside the data to make a better guess.
167 base, ext = posixpath.splitext(path)
168 if ext in self.extensions_map:
169 return self.extensions_map[ext]
171 if ext in self.extensions_map:
172 return self.extensions_map[ext]
174 return self.extensions_map['']
176 if not mimetypes.inited:
177 mimetypes.init() # try to read system mime.types
178 extensions_map = mimetypes.types_map.copy()
179 extensions_map.update({
180 '': 'text/plain', # Default
186 def date_time_string(self, t):
187 return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
192 def handle_sigterm(signum, frame):
194 debug1('\nbup-web: signal %d received\n' % signum)
195 log('Shutdown requested\n')
201 signal.signal(signal.SIGTERM, handle_sigterm)
203 UnixAddress = namedtuple('UnixAddress', ['path'])
204 InetAddress = namedtuple('InetAddress', ['host', 'port'])
207 bup web [[hostname]:port]
210 human-readable display human readable file sizes (i.e. 3.9K, 4.7M)
211 browser show repository in default browser (incompatible with unix://)
213 o = options.Options(optspec)
214 (opt, flags, extra) = o.parse(sys.argv[1:])
217 o.fatal("at most one argument expected")
220 address = InetAddress(host='127.0.0.1', port=8080)
223 if bind_url.startswith('unix://'):
224 address = UnixAddress(path=bind_url[len('unix://'):])
226 addr_parts = extra[0].split(':', 1)
227 if len(addr_parts) == 1:
231 host, port = addr_parts
234 except (TypeError, ValueError) as ex:
235 o.fatal('port must be an integer, not %r', port)
236 address = InetAddress(host=host, port=port)
238 git.check_repo_or_die()
239 top = vfs.RefList(None)
243 template_path = resource_path('web'),
244 static_path = resource_path('web/static')
247 # Disable buffering on stdout, for debug messages
248 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
250 application = tornado.web.Application([
251 (r"(/.*)", BupRequestHandler),
254 http_server = HTTPServer(application)
255 io_loop_pending = IOLoop.instance()
257 if isinstance(address, InetAddress):
258 http_server.listen(address.port, address.host)
260 sock = http_server._socket # tornado < 2.0
261 except AttributeError as e:
262 sock = http_server._sockets.values()[0]
263 print "Serving HTTP on %s:%d..." % sock.getsockname()
265 browser_addr = 'http://' + address[0] + ':' + str(address[1])
266 io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
267 elif isinstance(address, UnixAddress):
268 unix_socket = bind_unix_socket(address.path)
269 http_server.add_socket(unix_socket)
270 print "Serving HTTP on filesystem socket %r" % address.path
272 log('error: unexpected address %r', address)
275 io_loop = io_loop_pending
279 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))