]> arthur.barton.de Git - bup.git/blob - cmd/web-cmd.py
Add "bup rm", but require --unsafe invocation
[bup.git] / 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 import mimetypes, os, posixpath, stat, sys, time, urllib, webbrowser
9
10 from bup import options, git, vfs
11 from bup.helpers import debug1, handle_ctrl_c, log, resource_path
12
13 try:
14     import tornado.httpserver
15     import tornado.ioloop
16     import tornado.web
17 except ImportError:
18     log('error: cannot find the python "tornado" module; please install it\n')
19     sys.exit(1)
20
21
22 handle_ctrl_c()
23
24
25 def _compute_breadcrumbs(path, show_hidden=False):
26     """Returns a list of breadcrumb objects for a path."""
27     breadcrumbs = []
28     breadcrumbs.append(('[root]', '/'))
29     path_parts = path.split('/')[1:-1]
30     full_path = '/'
31     for part in path_parts:
32         full_path += part + "/"
33         url_append = ""
34         if show_hidden:
35             url_append = '?hidden=1'
36         breadcrumbs.append((part, full_path+url_append))
37     return breadcrumbs
38
39
40 def _contains_hidden_files(n):
41     """Return True if n contains files starting with a '.', False otherwise."""
42     for sub in n:
43         name = sub.name
44         if len(name)>1 and name.startswith('.'):
45             return True
46
47     return False
48
49
50 def _compute_dir_contents(n, path, show_hidden=False):
51     """Given a vfs node, returns an iterator for display info of all subs."""
52     url_append = ""
53     if show_hidden:
54         url_append = "?hidden=1"
55
56     if path != "/":
57         yield('..', '../' + url_append, '')
58     for sub in n:
59         display = sub.name
60         link = urllib.quote(sub.name)
61
62         # link should be based on fully resolved type to avoid extra
63         # HTTP redirect.
64         if stat.S_ISDIR(sub.try_resolve().mode):
65             link += "/"
66
67         if not show_hidden and len(display)>1 and display.startswith('.'):
68             continue
69
70         size = None
71         if stat.S_ISDIR(sub.mode):
72             display += '/'
73         elif stat.S_ISLNK(sub.mode):
74             display += '@'
75         else:
76             size = sub.size()
77             size = (opt.human_readable and format_filesize(size)) or size
78
79         yield (display, link + url_append, size)
80
81
82 class BupRequestHandler(tornado.web.RequestHandler):
83     def get(self, path):
84         return self._process_request(path)
85
86     def head(self, path):
87         return self._process_request(path)
88     
89     @tornado.web.asynchronous
90     def _process_request(self, path):
91         path = urllib.unquote(path)
92         print 'Handling request for %s' % path
93         try:
94             n = top.resolve(path)
95         except vfs.NoSuchFile:
96             self.send_error(404)
97             return
98         f = None
99         if stat.S_ISDIR(n.mode):
100             self._list_directory(path, n)
101         else:
102             self._get_file(path, n)
103
104     def _list_directory(self, path, n):
105         """Helper to produce a directory listing.
106
107         Return value is either a file object, or None (indicating an
108         error).  In either case, the headers are sent.
109         """
110         if not path.endswith('/') and len(path) > 0:
111             print 'Redirecting from %s to %s' % (path, path + '/')
112             return self.redirect(path + '/', permanent=True)
113
114         try:
115             show_hidden = int(self.request.arguments.get('hidden', [0])[-1])
116         except ValueError as e:
117             show_hidden = False
118
119         self.render(
120             'list-directory.html',
121             path=path,
122             breadcrumbs=_compute_breadcrumbs(path, show_hidden),
123             files_hidden=_contains_hidden_files(n),
124             hidden_shown=show_hidden,
125             dir_contents=_compute_dir_contents(n, path, show_hidden))
126
127     def _get_file(self, path, n):
128         """Process a request on a file.
129
130         Return value is either a file object, or None (indicating an error).
131         In either case, the headers are sent.
132         """
133         ctype = self._guess_type(path)
134
135         self.set_header("Last-Modified", self.date_time_string(n.mtime))
136         self.set_header("Content-Type", ctype)
137         size = n.size()
138         self.set_header("Content-Length", str(size))
139         assert(len(n.hash) == 20)
140         self.set_header("Etag", n.hash.encode('hex'))
141
142         if self.request.method != 'HEAD':
143             self.flush()
144             f = n.open()
145             it = chunkyreader(f)
146             def write_more(me):
147                 try:
148                     blob = it.next()
149                 except StopIteration:
150                     f.close()
151                     self.finish()
152                     return
153                 self.request.connection.stream.write(blob,
154                                                      callback=lambda: me(me))
155             write_more(write_more)
156         else:
157             self.finish()
158
159     def _guess_type(self, path):
160         """Guess the type of a file.
161
162         Argument is a PATH (a filename).
163
164         Return value is a string of the form type/subtype,
165         usable for a MIME Content-type header.
166
167         The default implementation looks the file's extension
168         up in the table self.extensions_map, using application/octet-stream
169         as a default; however it would be permissible (if
170         slow) to look inside the data to make a better guess.
171         """
172         base, ext = posixpath.splitext(path)
173         if ext in self.extensions_map:
174             return self.extensions_map[ext]
175         ext = ext.lower()
176         if ext in self.extensions_map:
177             return self.extensions_map[ext]
178         else:
179             return self.extensions_map['']
180
181     if not mimetypes.inited:
182         mimetypes.init() # try to read system mime.types
183     extensions_map = mimetypes.types_map.copy()
184     extensions_map.update({
185         '': 'text/plain', # Default
186         '.py': 'text/plain',
187         '.c': 'text/plain',
188         '.h': 'text/plain',
189         })
190
191     def date_time_string(self, t):
192         return time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime(t))
193
194
195 optspec = """
196 bup web [[hostname]:port]
197 --
198 human-readable    display human readable file sizes (i.e. 3.9K, 4.7M)
199 browser           open the site in the default browser
200 """
201 o = options.Options(optspec)
202 (opt, flags, extra) = o.parse(sys.argv[1:])
203
204 if len(extra) > 1:
205     o.fatal("at most one argument expected")
206
207 address = ('127.0.0.1', 8080)
208 if len(extra) > 0:
209     addressl = extra[0].split(':', 1)
210     addressl[1] = int(addressl[1])
211     address = tuple(addressl)
212
213 git.check_repo_or_die()
214 top = vfs.RefList(None)
215
216 settings = dict(
217     debug = 1,
218     template_path = resource_path('web'),
219     static_path = resource_path('web/static')
220 )
221
222 # Disable buffering on stdout, for debug messages
223 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
224
225 application = tornado.web.Application([
226     (r"(/.*)", BupRequestHandler),
227 ], **settings)
228
229 if __name__ == "__main__":
230     http_server = tornado.httpserver.HTTPServer(application)
231     http_server.listen(address[1], address=address[0])
232
233     try:
234         sock = http_server._socket # tornado < 2.0
235     except AttributeError as e:
236         sock = http_server._sockets.values()[0]
237
238     print "Serving HTTP on %s:%d..." % sock.getsockname()
239
240     loop = tornado.ioloop.IOLoop.instance()
241     if opt.browser:
242         browser_addr = 'http://' + address[0] + ':' + str(address[1])
243         loop.add_callback(lambda : webbrowser.open(browser_addr))
244     loop.start()