web.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. # web.py -- WSGI smart-http server
  2. # Copyright (C) 2010 Google, Inc.
  3. # Copyright (C) 2012 Jelmer Vernooij <jelmer@samba.org>
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; version 2
  8. # or (at your option) any later version of the License.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. """HTTP server for dulwich that implements the git smart HTTP protocol."""
  20. from cStringIO import StringIO
  21. import gzip
  22. import os
  23. import re
  24. import sys
  25. import time
  26. from urlparse import parse_qs
  27. from dulwich import log_utils
  28. from dulwich.protocol import (
  29. ReceivableProtocol,
  30. )
  31. from dulwich.repo import (
  32. Repo,
  33. )
  34. from dulwich.server import (
  35. DictBackend,
  36. DEFAULT_HANDLERS,
  37. generate_info_refs,
  38. generate_objects_info_packs,
  39. )
  40. logger = log_utils.getLogger(__name__)
  41. # HTTP error strings
  42. HTTP_OK = '200 OK'
  43. HTTP_NOT_FOUND = '404 Not Found'
  44. HTTP_FORBIDDEN = '403 Forbidden'
  45. HTTP_ERROR = '500 Internal Server Error'
  46. def date_time_string(timestamp=None):
  47. # From BaseHTTPRequestHandler.date_time_string in BaseHTTPServer.py in the
  48. # Python 2.6.5 standard library, following modifications:
  49. # - Made a global rather than an instance method.
  50. # - weekdayname and monthname are renamed and locals rather than class
  51. # variables.
  52. # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved
  53. weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  54. months = [None,
  55. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  56. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  57. if timestamp is None:
  58. timestamp = time.time()
  59. year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
  60. return '%s, %02d %3s %4d %02d:%02d:%02d GMD' % (
  61. weekdays[wd], day, months[month], year, hh, mm, ss)
  62. def url_prefix(mat):
  63. """Extract the URL prefix from a regex match.
  64. :param mat: A regex match object.
  65. :returns: The URL prefix, defined as the text before the match in the
  66. original string. Normalized to start with one leading slash and end with
  67. zero.
  68. """
  69. return '/' + mat.string[:mat.start()].strip('/')
  70. def get_repo(backend, mat):
  71. """Get a Repo instance for the given backend and URL regex match."""
  72. return backend.open_repository(url_prefix(mat))
  73. def send_file(req, f, content_type):
  74. """Send a file-like object to the request output.
  75. :param req: The HTTPGitRequest object to send output to.
  76. :param f: An open file-like object to send; will be closed.
  77. :param content_type: The MIME type for the file.
  78. :return: Iterator over the contents of the file, as chunks.
  79. """
  80. if f is None:
  81. yield req.not_found('File not found')
  82. return
  83. try:
  84. req.respond(HTTP_OK, content_type)
  85. while True:
  86. data = f.read(10240)
  87. if not data:
  88. break
  89. yield data
  90. f.close()
  91. except IOError:
  92. f.close()
  93. yield req.error('Error reading file')
  94. except:
  95. f.close()
  96. raise
  97. def _url_to_path(url):
  98. return url.replace('/', os.path.sep)
  99. def get_text_file(req, backend, mat):
  100. req.nocache()
  101. path = _url_to_path(mat.group())
  102. logger.info('Sending plain text file %s', path)
  103. return send_file(req, get_repo(backend, mat).get_named_file(path),
  104. 'text/plain')
  105. def get_loose_object(req, backend, mat):
  106. sha = mat.group(1) + mat.group(2)
  107. logger.info('Sending loose object %s', sha)
  108. object_store = get_repo(backend, mat).object_store
  109. if not object_store.contains_loose(sha):
  110. yield req.not_found('Object not found')
  111. return
  112. try:
  113. data = object_store[sha].as_legacy_object()
  114. except IOError:
  115. yield req.error('Error reading object')
  116. return
  117. req.cache_forever()
  118. req.respond(HTTP_OK, 'application/x-git-loose-object')
  119. yield data
  120. def get_pack_file(req, backend, mat):
  121. req.cache_forever()
  122. path = _url_to_path(mat.group())
  123. logger.info('Sending pack file %s', path)
  124. return send_file(req, get_repo(backend, mat).get_named_file(path),
  125. 'application/x-git-packed-objects')
  126. def get_idx_file(req, backend, mat):
  127. req.cache_forever()
  128. path = _url_to_path(mat.group())
  129. logger.info('Sending pack file %s', path)
  130. return send_file(req, get_repo(backend, mat).get_named_file(path),
  131. 'application/x-git-packed-objects-toc')
  132. def get_info_refs(req, backend, mat):
  133. params = parse_qs(req.environ['QUERY_STRING'])
  134. service = params.get('service', [None])[0]
  135. if service and not req.dumb:
  136. handler_cls = req.handlers.get(service, None)
  137. if handler_cls is None:
  138. yield req.forbidden('Unsupported service %s' % service)
  139. return
  140. req.nocache()
  141. write = req.respond(HTTP_OK, 'application/x-%s-advertisement' % service)
  142. proto = ReceivableProtocol(StringIO().read, write)
  143. handler = handler_cls(backend, [url_prefix(mat)], proto,
  144. http_req=req, advertise_refs=True)
  145. handler.proto.write_pkt_line('# service=%s\n' % service)
  146. handler.proto.write_pkt_line(None)
  147. handler.handle()
  148. else:
  149. # non-smart fallback
  150. # TODO: select_getanyfile() (see http-backend.c)
  151. req.nocache()
  152. req.respond(HTTP_OK, 'text/plain')
  153. logger.info('Emulating dumb info/refs')
  154. repo = get_repo(backend, mat)
  155. for text in generate_info_refs(repo):
  156. yield text
  157. def get_info_packs(req, backend, mat):
  158. req.nocache()
  159. req.respond(HTTP_OK, 'text/plain')
  160. logger.info('Emulating dumb info/packs')
  161. return generate_objects_info_packs(get_repo(backend, mat))
  162. class _LengthLimitedFile(object):
  163. """Wrapper class to limit the length of reads from a file-like object.
  164. This is used to ensure EOF is read from the wsgi.input object once
  165. Content-Length bytes are read. This behavior is required by the WSGI spec
  166. but not implemented in wsgiref as of 2.5.
  167. """
  168. def __init__(self, input, max_bytes):
  169. self._input = input
  170. self._bytes_avail = max_bytes
  171. def read(self, size=-1):
  172. if self._bytes_avail <= 0:
  173. return ''
  174. if size == -1 or size > self._bytes_avail:
  175. size = self._bytes_avail
  176. self._bytes_avail -= size
  177. return self._input.read(size)
  178. # TODO: support more methods as necessary
  179. def handle_service_request(req, backend, mat):
  180. service = mat.group().lstrip('/')
  181. logger.info('Handling service request for %s', service)
  182. handler_cls = req.handlers.get(service, None)
  183. if handler_cls is None:
  184. yield req.forbidden('Unsupported service %s' % service)
  185. return
  186. req.nocache()
  187. write = req.respond(HTTP_OK, 'application/x-%s-result' % service)
  188. proto = ReceivableProtocol(req.environ['wsgi.input'].read, write)
  189. handler = handler_cls(backend, [url_prefix(mat)], proto, http_req=req)
  190. handler.handle()
  191. class HTTPGitRequest(object):
  192. """Class encapsulating the state of a single git HTTP request.
  193. :ivar environ: the WSGI environment for the request.
  194. """
  195. def __init__(self, environ, start_response, dumb=False, handlers=None):
  196. self.environ = environ
  197. self.dumb = dumb
  198. self.handlers = handlers
  199. self._start_response = start_response
  200. self._cache_headers = []
  201. self._headers = []
  202. def add_header(self, name, value):
  203. """Add a header to the response."""
  204. self._headers.append((name, value))
  205. def respond(self, status=HTTP_OK, content_type=None, headers=None):
  206. """Begin a response with the given status and other headers."""
  207. if headers:
  208. self._headers.extend(headers)
  209. if content_type:
  210. self._headers.append(('Content-Type', content_type))
  211. self._headers.extend(self._cache_headers)
  212. return self._start_response(status, self._headers)
  213. def not_found(self, message):
  214. """Begin a HTTP 404 response and return the text of a message."""
  215. self._cache_headers = []
  216. logger.info('Not found: %s', message)
  217. self.respond(HTTP_NOT_FOUND, 'text/plain')
  218. return message
  219. def forbidden(self, message):
  220. """Begin a HTTP 403 response and return the text of a message."""
  221. self._cache_headers = []
  222. logger.info('Forbidden: %s', message)
  223. self.respond(HTTP_FORBIDDEN, 'text/plain')
  224. return message
  225. def error(self, message):
  226. """Begin a HTTP 500 response and return the text of a message."""
  227. self._cache_headers = []
  228. logger.error('Error: %s', message)
  229. self.respond(HTTP_ERROR, 'text/plain')
  230. return message
  231. def nocache(self):
  232. """Set the response to never be cached by the client."""
  233. self._cache_headers = [
  234. ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'),
  235. ('Pragma', 'no-cache'),
  236. ('Cache-Control', 'no-cache, max-age=0, must-revalidate'),
  237. ]
  238. def cache_forever(self):
  239. """Set the response to be cached forever by the client."""
  240. now = time.time()
  241. self._cache_headers = [
  242. ('Date', date_time_string(now)),
  243. ('Expires', date_time_string(now + 31536000)),
  244. ('Cache-Control', 'public, max-age=31536000'),
  245. ]
  246. class HTTPGitApplication(object):
  247. """Class encapsulating the state of a git WSGI application.
  248. :ivar backend: the Backend object backing this application
  249. """
  250. services = {
  251. ('GET', re.compile('/HEAD$')): get_text_file,
  252. ('GET', re.compile('/info/refs$')): get_info_refs,
  253. ('GET', re.compile('/objects/info/alternates$')): get_text_file,
  254. ('GET', re.compile('/objects/info/http-alternates$')): get_text_file,
  255. ('GET', re.compile('/objects/info/packs$')): get_info_packs,
  256. ('GET', re.compile('/objects/([0-9a-f]{2})/([0-9a-f]{38})$')): get_loose_object,
  257. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.pack$')): get_pack_file,
  258. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.idx$')): get_idx_file,
  259. ('POST', re.compile('/git-upload-pack$')): handle_service_request,
  260. ('POST', re.compile('/git-receive-pack$')): handle_service_request,
  261. }
  262. def __init__(self, backend, dumb=False, handlers=None, fallback_app=None):
  263. self.backend = backend
  264. self.dumb = dumb
  265. self.handlers = dict(DEFAULT_HANDLERS)
  266. self.fallback_app = fallback_app
  267. if handlers is not None:
  268. self.handlers.update(handlers)
  269. def __call__(self, environ, start_response):
  270. path = environ['PATH_INFO']
  271. method = environ['REQUEST_METHOD']
  272. req = HTTPGitRequest(environ, start_response, dumb=self.dumb,
  273. handlers=self.handlers)
  274. # environ['QUERY_STRING'] has qs args
  275. handler = None
  276. for smethod, spath in self.services.iterkeys():
  277. if smethod != method:
  278. continue
  279. mat = spath.search(path)
  280. if mat:
  281. handler = self.services[smethod, spath]
  282. break
  283. if handler is None:
  284. if self.fallback_app is not None:
  285. return self.fallback_app(environ, start_response)
  286. else:
  287. return req.not_found('Sorry, that method is not supported')
  288. return handler(req, self.backend, mat)
  289. class GunzipFilter(object):
  290. """WSGI middleware that unzips gzip-encoded requests before
  291. passing on to the underlying application.
  292. """
  293. def __init__(self, application):
  294. self.app = application
  295. def __call__(self, environ, start_response):
  296. if environ.get('HTTP_CONTENT_ENCODING', '') == 'gzip':
  297. environ.pop('HTTP_CONTENT_ENCODING')
  298. if 'CONTENT_LENGTH' in environ:
  299. del environ['CONTENT_LENGTH']
  300. environ['wsgi.input'] = gzip.GzipFile(filename=None,
  301. fileobj=environ['wsgi.input'], mode='r')
  302. return self.app(environ, start_response)
  303. class LimitedInputFilter(object):
  304. """WSGI middleware that limits the input length of a request to that
  305. specified in Content-Length.
  306. """
  307. def __init__(self, application):
  308. self.app = application
  309. def __call__(self, environ, start_response):
  310. # This is not necessary if this app is run from a conforming WSGI
  311. # server. Unfortunately, there's no way to tell that at this point.
  312. # TODO: git may used HTTP/1.1 chunked encoding instead of specifying
  313. # content-length
  314. content_length = environ.get('CONTENT_LENGTH', '')
  315. if content_length:
  316. environ['wsgi.input'] = _LengthLimitedFile(
  317. environ['wsgi.input'], int(content_length))
  318. return self.app(environ, start_response)
  319. def make_wsgi_chain(*args, **kwargs):
  320. """Factory function to create an instance of HTTPGitApplication,
  321. correctly wrapped with needed middleware.
  322. """
  323. app = HTTPGitApplication(*args, **kwargs)
  324. wrapped_app = GunzipFilter(LimitedInputFilter(app))
  325. return wrapped_app
  326. # The reference server implementation is based on wsgiref, which is not
  327. # distributed with python 2.4. If wsgiref is not present, users will not be
  328. # able to use the HTTP server without a little extra work.
  329. try:
  330. from wsgiref.simple_server import (
  331. WSGIRequestHandler,
  332. ServerHandler,
  333. WSGIServer,
  334. make_server,
  335. )
  336. class ServerHandlerLogger(ServerHandler):
  337. """ServerHandler that uses dulwich's logger for logging exceptions."""
  338. def log_exception(self, exc_info):
  339. logger.exception('Exception happened during processing of request',
  340. exc_info=exc_info)
  341. def log_message(self, format, *args):
  342. logger.info(format, *args)
  343. def log_error(self, *args):
  344. logger.error(*args)
  345. class WSGIRequestHandlerLogger(WSGIRequestHandler):
  346. """WSGIRequestHandler that uses dulwich's logger for logging exceptions."""
  347. def log_exception(self, exc_info):
  348. logger.exception('Exception happened during processing of request',
  349. exc_info=exc_info)
  350. def log_message(self, format, *args):
  351. logger.info(format, *args)
  352. def log_error(self, *args):
  353. logger.error(*args)
  354. def handle(self):
  355. """Handle a single HTTP request"""
  356. self.raw_requestline = self.rfile.readline()
  357. if not self.parse_request(): # An error code has been sent, just exit
  358. return
  359. handler = ServerHandlerLogger(
  360. self.rfile, self.wfile, self.get_stderr(), self.get_environ()
  361. )
  362. handler.request_handler = self # backpointer for logging
  363. handler.run(self.server.get_app())
  364. class WSGIServerLogger(WSGIServer):
  365. def handle_error(self, request, client_address):
  366. """Handle an error. """
  367. logger.exception('Exception happened during processing of request from %s' % str(client_address))
  368. def main(argv=sys.argv):
  369. """Entry point for starting an HTTP git server."""
  370. if len(argv) > 1:
  371. gitdir = argv[1]
  372. else:
  373. gitdir = os.getcwd()
  374. # TODO: allow serving on other addresses/ports via command-line flag
  375. listen_addr = ''
  376. port = 8000
  377. log_utils.default_logging_config()
  378. backend = DictBackend({'/': Repo(gitdir)})
  379. app = make_wsgi_chain(backend)
  380. server = make_server(listen_addr, port, app,
  381. handler_class=WSGIRequestHandlerLogger,
  382. server_class=WSGIServerLogger)
  383. logger.info('Listening for HTTP connections on %s:%d', listen_addr,
  384. port)
  385. server.serve_forever()
  386. except ImportError:
  387. # No wsgiref found; don't provide the reference functionality, but leave
  388. # the rest of the WSGI-based implementation.
  389. def main(argv=sys.argv):
  390. """Stub entry point for failing to start a server without wsgiref."""
  391. sys.stderr.write(
  392. 'Sorry, the wsgiref module is required for dul-web.\n')
  393. sys.exit(1)
  394. if __name__ == '__main__':
  395. main()