web.py 17 KB

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