PageRenderTime 57ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/observatory/lib/dulwich/web.py

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