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.httpserver import HTTPServer
17 from tornado.ioloop import IOLoop
18 from tornado.netutil import bind_unix_socket
21 log('error: cannot find the python "tornado" module; please install it\n')
28 def _compute_breadcrumbs(path, show_hidden=False):
29 """Returns a list of breadcrumb objects for a path."""
31 breadcrumbs.append(('[root]', '/'))
32 path_parts = path.split('/')[1:-1]
34 for part in path_parts:
35 full_path += part + "/"
38 url_append = '?hidden=1'
39 breadcrumbs.append((part, full_path+url_append))
43 def _contains_hidden_files(n):
44 """Return True if n contains files starting with a '.', False otherwise."""
47 if len(name)>1 and name.startswith('.'):
53 def _compute_dir_contents(n, path, show_hidden=False):
54 """Given a vfs node, returns an iterator for display info of all subs."""
57 url_append = "?hidden=1"
60 yield('..', '../' + url_append, '')
63 link = urllib.quote(sub.name)
65 # link should be based on fully resolved type to avoid extra
67 if stat.S_ISDIR(sub.try_resolve().mode):
70 if not show_hidden and len(display)>1 and display.startswith('.'):
74 if stat.S_ISDIR(sub.mode):
76 elif stat.S_ISLNK(sub.mode):
80 size = (opt.human_readable and format_filesize(size)) or size
82 yield (display, link + url_append, size)
85 class BupRequestHandler(tornado.web.RequestHandler):
87 return self._process_request(path)
90 return self._process_request(path)
92 @tornado.web.asynchronous
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))
130 def _get_file(self, path, n):
131 """Process a request on a file.
133 Return value is either a file object, or None (indicating an error).
134 In either case, the headers are sent.
136 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'))
145 if self.request.method != 'HEAD':
152 except StopIteration:
156 self.request.connection.stream.write(blob,
157 callback=lambda: me(me))
158 write_more(write_more)
162 def _guess_type(self, path):
163 """Guess the type of a file.
165 Argument is a PATH (a filename).
167 Return value is a string of the form type/subtype,
168 usable for a MIME Content-type header.
170 The default implementation looks the file's extension
171 up in the table self.extensions_map, using application/octet-stream
172 as a default; however it would be permissible (if
173 slow) to look inside the data to make a better guess.
175 base, ext = posixpath.splitext(path)
176 if ext in self.extensions_map:
177 return self.extensions_map[ext]
179 if ext in self.extensions_map:
180 return self.extensions_map[ext]
182 return self.extensions_map['']
184 if not mimetypes.inited:
185 mimetypes.init() # try to read system mime.types
186 extensions_map = mimetypes.types_map.copy()
187 extensions_map.update({
188 '': 'text/plain', # Default
194 def date_time_string(self, t):
195 return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
200 def handle_sigterm(signum, frame):
202 debug1('\nbup-web: signal %d received\n' % signum)
203 log('Shutdown requested\n')
209 signal.signal(signal.SIGTERM, handle_sigterm)
211 UnixAddress = namedtuple('UnixAddress', ['path'])
212 InetAddress = namedtuple('InetAddress', ['host', 'port'])
215 bup web [[hostname]:port]
218 human-readable display human readable file sizes (i.e. 3.9K, 4.7M)
219 browser show repository in default browser (incompatible with unix://)
221 o = options.Options(optspec)
222 (opt, flags, extra) = o.parse(sys.argv[1:])
225 o.fatal("at most one argument expected")
228 address = InetAddress(host='127.0.0.1', port=8080)
231 if bind_url.startswith('unix://'):
232 address = UnixAddress(path=bind_url[len('unix://'):])
234 addr_parts = extra[0].split(':', 1)
235 if len(addr_parts) == 1:
239 host, port = addr_parts
242 except (TypeError, ValueError) as ex:
243 o.fatal('port must be an integer, not %r', port)
244 address = InetAddress(host=host, port=port)
246 git.check_repo_or_die()
247 top = vfs.RefList(None)
251 template_path = resource_path('web'),
252 static_path = resource_path('web/static')
255 # Disable buffering on stdout, for debug messages
256 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
258 application = tornado.web.Application([
259 (r"(/.*)", BupRequestHandler),
262 http_server = HTTPServer(application)
263 io_loop_pending = IOLoop.instance()
265 if isinstance(address, InetAddress):
266 http_server.listen(address.port, address.host)
268 sock = http_server._socket # tornado < 2.0
269 except AttributeError as e:
270 sock = http_server._sockets.values()[0]
271 print "Serving HTTP on %s:%d..." % sock.getsockname()
273 browser_addr = 'http://' + address[0] + ':' + str(address[1])
274 io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
275 elif isinstance(address, UnixAddress):
276 unix_socket = bind_unix_socket(address.path)
277 http_server.add_socket(unix_socket)
278 print "Serving HTTP on filesystem socket %r" % address.path
280 log('error: unexpected address %r', address)
283 io_loop = io_loop_pending
287 log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))