web.py 17 KB

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