web.py 15 KB

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