]> arthur.barton.de Git - bup.git/blob - lib/cmd/web-cmd.py
Move cmd to lib/ and reverse symlink
[bup.git] / lib / cmd / web-cmd.py
1 #!/bin/sh
2 """": # -*-python-*-
3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
5 """
6 # end of bup preamble
7
8 from __future__ import absolute_import, print_function
9 from collections import namedtuple
10 import mimetypes, os, posixpath, signal, stat, sys, time, urllib, webbrowser
11
12 from bup import options, git, vfs
13 from bup.helpers import (chunkyreader, debug1, format_filesize, handle_ctrl_c,
14                          log, saved_errors)
15 from bup.metadata import Metadata
16 from bup.path import resource_path
17 from bup.repo import LocalRepo
18
19 try:
20     from tornado import gen
21     from tornado.httpserver import HTTPServer
22     from tornado.ioloop import IOLoop
23     from tornado.netutil import bind_unix_socket
24     import tornado.web
25 except ImportError:
26     log('error: cannot find the python "tornado" module; please install it\n')
27     sys.exit(1)
28
29
30 # FIXME: right now the way hidden files are handled causes every
31 # directory to be traversed twice.
32
33 handle_ctrl_c()
34
35
36 def http_date_from_utc_ns(utc_ns):
37     return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(utc_ns / 10**9))
38
39
40 def _compute_breadcrumbs(path, show_hidden=False):
41     """Returns a list of breadcrumb objects for a path."""
42     breadcrumbs = []
43     breadcrumbs.append(('[root]', '/'))
44     path_parts = path.split('/')[1:-1]
45     full_path = '/'
46     for part in path_parts:
47         full_path += part + "/"
48         url_append = ""
49         if show_hidden:
50             url_append = '?hidden=1'
51         breadcrumbs.append((part, full_path+url_append))
52     return breadcrumbs
53
54
55 def _contains_hidden_files(repo, dir_item):
56     """Return true if the directory contains items with names other than
57     '.' and '..' that begin with '.'
58
59     """
60     for name, item in vfs.contents(repo, dir_item, want_meta=False):
61         if name in ('.', '..'):
62             continue
63         if name.startswith('.'):
64             return True
65     return False
66
67
68 def _dir_contents(repo, resolution, show_hidden=False):
69     """Yield the display information for the contents of dir_item."""
70
71     url_query = '?hidden=1' if show_hidden else ''
72
73     def display_info(name, item, resolved_item, display_name=None):
74         # link should be based on fully resolved type to avoid extra
75         # HTTP redirect.
76         if stat.S_ISDIR(vfs.item_mode(resolved_item)):
77             link = urllib.quote(name) + '/'
78         else:
79             link = urllib.quote(name)
80
81         size = vfs.item_size(repo, item)
82         if opt.human_readable:
83             display_size = format_filesize(size)
84         else:
85             display_size = size
86
87         if not display_name:
88             mode = vfs.item_mode(item)
89             if stat.S_ISDIR(mode):
90                 display_name = name + '/'
91             elif stat.S_ISLNK(mode):
92                 display_name = name + '@'
93             else:
94                 display_name = name
95
96         return display_name, link + url_query, display_size
97
98     dir_item = resolution[-1][1]    
99     for name, item in vfs.contents(repo, dir_item):
100         if not show_hidden:
101             if (name not in ('.', '..')) and name.startswith('.'):
102                 continue
103         if name == '.':
104             yield display_info(name, item, item, '.')
105             parent_item = resolution[-2][1] if len(resolution) > 1 else dir_item
106             yield display_info('..', parent_item, parent_item, '..')
107             continue
108         res = vfs.try_resolve(repo, name, parent=resolution, want_meta=False)
109         res_name, res_item = res[-1]
110         yield display_info(name, item, res_item)
111
112
113 class BupRequestHandler(tornado.web.RequestHandler):
114
115     def initialize(self, repo=None):
116         self.repo = repo
117
118     def decode_argument(self, value, name=None):
119         if name == 'path':
120             return value
121         return super(BupRequestHandler, self).decode_argument(value, name)
122
123     def get(self, path):
124         return self._process_request(path)
125
126     def head(self, path):
127         return self._process_request(path)
128     
129     def _process_request(self, path):
130         path = urllib.unquote(path)
131         print('Handling request for %s' % path)
132         # Set want_meta because dir metadata won't be fetched, and if
133         # it's not a dir, then we're going to want the metadata.
134         res = vfs.resolve(self.repo, path, want_meta=True)
135         leaf_name, leaf_item = res[-1]
136         if not leaf_item:
137             self.send_error(404)
138             return
139         mode = vfs.item_mode(leaf_item)
140         if stat.S_ISDIR(mode):
141             self._list_directory(path, res)
142         else:
143             self._get_file(self.repo, path, res)
144
145     def _list_directory(self, path, resolution):
146         """Helper to produce a directory listing.
147
148         Return value is either a file object, or None (indicating an
149         error).  In either case, the headers are sent.
150         """
151         if not path.endswith('/') and len(path) > 0:
152             print('Redirecting from %s to %s' % (path, path + '/'))
153             return self.redirect(path + '/', permanent=True)
154
155         hidden_arg = self.request.arguments.get('hidden', [0])[-1]
156         try:
157             show_hidden = int(hidden_arg)
158         except ValueError as e:
159             show_hidden = False
160
161         self.render(
162             'list-directory.html',
163             path=path,
164             breadcrumbs=_compute_breadcrumbs(path, show_hidden),
165             files_hidden=_contains_hidden_files(self.repo, resolution[-1][1]),
166             hidden_shown=show_hidden,
167             dir_contents=_dir_contents(self.repo, resolution,
168                                        show_hidden=show_hidden))
169
170     @gen.coroutine
171     def _get_file(self, repo, path, resolved):
172         """Process a request on a file.
173
174         Return value is either a file object, or None (indicating an error).
175         In either case, the headers are sent.
176         """
177         file_item = resolved[-1][1]
178         file_item = vfs.augment_item_meta(repo, file_item, include_size=True)
179         meta = file_item.meta
180         ctype = self._guess_type(path)
181         self.set_header("Last-Modified", http_date_from_utc_ns(meta.mtime))
182         self.set_header("Content-Type", ctype)
183         
184         self.set_header("Content-Length", str(meta.size))
185         assert len(file_item.oid) == 20
186         self.set_header("Etag", file_item.oid.encode('hex'))
187         if self.request.method != 'HEAD':
188             with vfs.fopen(self.repo, file_item) as f:
189                 it = chunkyreader(f)
190                 for blob in chunkyreader(f):
191                     self.write(blob)
192         raise gen.Return()
193
194     def _guess_type(self, path):
195         """Guess the type of a file.
196
197         Argument is a PATH (a filename).
198
199         Return value is a string of the form type/subtype,
200         usable for a MIME Content-type header.
201
202         The default implementation looks the file's extension
203         up in the table self.extensions_map, using application/octet-stream
204         as a default; however it would be permissible (if
205         slow) to look inside the data to make a better guess.
206         """
207         base, ext = posixpath.splitext(path)
208         if ext in self.extensions_map:
209             return self.extensions_map[ext]
210         ext = ext.lower()
211         if ext in self.extensions_map:
212             return self.extensions_map[ext]
213         else:
214             return self.extensions_map['']
215
216     if not mimetypes.inited:
217         mimetypes.init() # try to read system mime.types
218     extensions_map = mimetypes.types_map.copy()
219     extensions_map.update({
220         '': 'text/plain', # Default
221         '.py': 'text/plain',
222         '.c': 'text/plain',
223         '.h': 'text/plain',
224         })
225
226
227 io_loop = None
228
229 def handle_sigterm(signum, frame):
230     global io_loop
231     debug1('\nbup-web: signal %d received\n' % signum)
232     log('Shutdown requested\n')
233     if not io_loop:
234         sys.exit(0)
235     io_loop.stop()
236
237
238 signal.signal(signal.SIGTERM, handle_sigterm)
239
240 UnixAddress = namedtuple('UnixAddress', ['path'])
241 InetAddress = namedtuple('InetAddress', ['host', 'port'])
242
243 optspec = """
244 bup web [[hostname]:port]
245 bup web unix://path
246 --
247 human-readable    display human readable file sizes (i.e. 3.9K, 4.7M)
248 browser           show repository in default browser (incompatible with unix://)
249 """
250 o = options.Options(optspec)
251 (opt, flags, extra) = o.parse(sys.argv[1:])
252
253 if len(extra) > 1:
254     o.fatal("at most one argument expected")
255
256 if len(extra) == 0:
257     address = InetAddress(host='127.0.0.1', port=8080)
258 else:
259     bind_url = extra[0]
260     if bind_url.startswith('unix://'):
261         address = UnixAddress(path=bind_url[len('unix://'):])
262     else:
263         addr_parts = extra[0].split(':', 1)
264         if len(addr_parts) == 1:
265             host = '127.0.0.1'
266             port = addr_parts[0]
267         else:
268             host, port = addr_parts
269         try:
270             port = int(port)
271         except (TypeError, ValueError) as ex:
272             o.fatal('port must be an integer, not %r' % port)
273         address = InetAddress(host=host, port=port)
274
275 git.check_repo_or_die()
276
277 settings = dict(
278     debug = 1,
279     template_path = resource_path('web'),
280     static_path = resource_path('web/static')
281 )
282
283 # Disable buffering on stdout, for debug messages
284 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
285
286 application = tornado.web.Application([
287     (r"(?P<path>/.*)", BupRequestHandler, dict(repo=LocalRepo())),
288 ], **settings)
289
290 http_server = HTTPServer(application)
291 io_loop_pending = IOLoop.instance()
292
293 if isinstance(address, InetAddress):
294     http_server.listen(address.port, address.host)
295     try:
296         sock = http_server._socket # tornado < 2.0
297     except AttributeError as e:
298         sock = http_server._sockets.values()[0]
299     print('Serving HTTP on %s:%d...' % sock.getsockname())
300     if opt.browser:
301         browser_addr = 'http://' + address[0] + ':' + str(address[1])
302         io_loop_pending.add_callback(lambda : webbrowser.open(browser_addr))
303 elif isinstance(address, UnixAddress):
304     unix_socket = bind_unix_socket(address.path)
305     http_server.add_socket(unix_socket)
306     print('Serving HTTP on filesystem socket %r' % address.path)
307 else:
308     log('error: unexpected address %r', address)
309     sys.exit(1)
310
311 io_loop = io_loop_pending
312 io_loop.start()
313
314 if saved_errors:
315     log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
316     sys.exit(1)