web.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 time
  23. try:
  24. from urlparse import parse_qs
  25. except ImportError:
  26. from dulwich.misc import parse_qs
  27. from dulwich import log_utils
  28. from dulwich.protocol import (
  29. ReceivableProtocol,
  30. )
  31. from dulwich.server import (
  32. DEFAULT_HANDLERS,
  33. )
  34. logger = log_utils.getLogger(__name__)
  35. # HTTP error strings
  36. HTTP_OK = '200 OK'
  37. HTTP_NOT_FOUND = '404 Not Found'
  38. HTTP_FORBIDDEN = '403 Forbidden'
  39. def date_time_string(timestamp=None):
  40. # Based on BaseHTTPServer.py in python2.5
  41. weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  42. months = [None,
  43. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  44. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  45. if timestamp is None:
  46. timestamp = time.time()
  47. year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
  48. return '%s, %02d %3s %4d %02d:%02d:%02d GMD' % (
  49. weekdays[wd], day, months[month], year, hh, mm, ss)
  50. def url_prefix(mat):
  51. """Extract the URL prefix from a regex match.
  52. :param mat: A regex match object.
  53. :returns: The URL prefix, defined as the text before the match in the
  54. original string. Normalized to start with one leading slash and end with
  55. zero.
  56. """
  57. return '/' + mat.string[:mat.start()].strip('/')
  58. def get_repo(backend, mat):
  59. """Get a Repo instance for the given backend and URL regex match."""
  60. return backend.open_repository(url_prefix(mat))
  61. def send_file(req, f, content_type):
  62. """Send a file-like object to the request output.
  63. :param req: The HTTPGitRequest object to send output to.
  64. :param f: An open file-like object to send; will be closed.
  65. :param content_type: The MIME type for the file.
  66. :yield: The contents of the file.
  67. """
  68. if f is None:
  69. yield req.not_found('File not found')
  70. return
  71. try:
  72. req.respond(HTTP_OK, content_type)
  73. while True:
  74. data = f.read(10240)
  75. if not data:
  76. break
  77. yield data
  78. f.close()
  79. except IOError:
  80. f.close()
  81. yield req.not_found('Error reading file')
  82. except:
  83. f.close()
  84. raise
  85. def _url_to_path(url):
  86. return url.replace('/', os.path.sep)
  87. def get_text_file(req, backend, mat):
  88. req.nocache()
  89. path = _url_to_path(mat.group())
  90. logger.info('Sending plain text file %s', path)
  91. return send_file(req, get_repo(backend, mat).get_named_file(path),
  92. 'text/plain')
  93. def get_loose_object(req, backend, mat):
  94. sha = mat.group(1) + mat.group(2)
  95. logger.info('Sending loose object %s', sha)
  96. object_store = get_repo(backend, mat).object_store
  97. if not object_store.contains_loose(sha):
  98. yield req.not_found('Object not found')
  99. return
  100. try:
  101. data = object_store[sha].as_legacy_object()
  102. except IOError:
  103. yield req.not_found('Error reading object')
  104. req.cache_forever()
  105. req.respond(HTTP_OK, 'application/x-git-loose-object')
  106. yield data
  107. def get_pack_file(req, backend, mat):
  108. req.cache_forever()
  109. path = _url_to_path(mat.group())
  110. logger.info('Sending pack file %s', path)
  111. return send_file(req, get_repo(backend, mat).get_named_file(path),
  112. 'application/x-git-packed-objects')
  113. def get_idx_file(req, backend, mat):
  114. req.cache_forever()
  115. path = _url_to_path(mat.group())
  116. logger.info('Sending pack file %s', path)
  117. return send_file(req, get_repo(backend, mat).get_named_file(path),
  118. 'application/x-git-packed-objects-toc')
  119. def get_info_refs(req, backend, mat):
  120. params = parse_qs(req.environ['QUERY_STRING'])
  121. service = params.get('service', [None])[0]
  122. if service and not req.dumb:
  123. handler_cls = req.handlers.get(service, None)
  124. if handler_cls is None:
  125. yield req.forbidden('Unsupported service %s' % service)
  126. return
  127. req.nocache()
  128. req.respond(HTTP_OK, 'application/x-%s-advertisement' % service)
  129. output = StringIO()
  130. proto = ReceivableProtocol(StringIO().read, output.write)
  131. handler = handler_cls(backend, [url_prefix(mat)], proto,
  132. stateless_rpc=True, advertise_refs=True)
  133. handler.proto.write_pkt_line('# service=%s\n' % service)
  134. handler.proto.write_pkt_line(None)
  135. handler.handle()
  136. yield output.getvalue()
  137. else:
  138. # non-smart fallback
  139. # TODO: select_getanyfile() (see http-backend.c)
  140. req.nocache()
  141. req.respond(HTTP_OK, 'text/plain')
  142. logger.info('Emulating dumb info/refs')
  143. repo = get_repo(backend, mat)
  144. refs = repo.get_refs()
  145. for name in sorted(refs.iterkeys()):
  146. # get_refs() includes HEAD as a special case, but we don't want to
  147. # advertise it
  148. if name == 'HEAD':
  149. continue
  150. sha = refs[name]
  151. o = repo[sha]
  152. if not o:
  153. continue
  154. yield '%s\t%s\n' % (sha, name)
  155. peeled_sha = repo.get_peeled(name)
  156. if peeled_sha != sha:
  157. yield '%s\t%s^{}\n' % (peeled_sha, name)
  158. def get_info_packs(req, backend, mat):
  159. req.nocache()
  160. req.respond(HTTP_OK, 'text/plain')
  161. logger.info('Emulating dumb info/packs')
  162. for pack in get_repo(backend, mat).object_store.packs:
  163. yield 'P pack-%s.pack\n' % pack.name()
  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. req.respond(HTTP_OK, 'application/x-%s-response' % service)
  190. output = StringIO()
  191. input = req.environ['wsgi.input']
  192. # This is not necessary if this app is run from a conforming WSGI server.
  193. # Unfortunately, there's no way to tell that at this point.
  194. # TODO: git may used HTTP/1.1 chunked encoding instead of specifying
  195. # content-length
  196. if 'CONTENT_LENGTH' in req.environ:
  197. input = _LengthLimitedFile(input, int(req.environ['CONTENT_LENGTH']))
  198. proto = ReceivableProtocol(input.read, output.write)
  199. handler = handler_cls(backend, [url_prefix(mat)], proto, stateless_rpc=True)
  200. handler.handle()
  201. yield output.getvalue()
  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 and handlers or DEFAULT_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. 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 nocache(self):
  237. """Set the response to never be cached by the client."""
  238. self._cache_headers = [
  239. ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'),
  240. ('Pragma', 'no-cache'),
  241. ('Cache-Control', 'no-cache, max-age=0, must-revalidate'),
  242. ]
  243. def cache_forever(self):
  244. """Set the response to be cached forever by the client."""
  245. now = time.time()
  246. self._cache_headers = [
  247. ('Date', date_time_string(now)),
  248. ('Expires', date_time_string(now + 31536000)),
  249. ('Cache-Control', 'public, max-age=31536000'),
  250. ]
  251. class HTTPGitApplication(object):
  252. """Class encapsulating the state of a git WSGI application.
  253. :ivar backend: the Backend object backing this application
  254. """
  255. services = {
  256. ('GET', re.compile('/HEAD$')): get_text_file,
  257. ('GET', re.compile('/info/refs$')): get_info_refs,
  258. ('GET', re.compile('/objects/info/alternates$')): get_text_file,
  259. ('GET', re.compile('/objects/info/http-alternates$')): get_text_file,
  260. ('GET', re.compile('/objects/info/packs$')): get_info_packs,
  261. ('GET', re.compile('/objects/([0-9a-f]{2})/([0-9a-f]{38})$')): get_loose_object,
  262. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.pack$')): get_pack_file,
  263. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.idx$')): get_idx_file,
  264. ('POST', re.compile('/git-upload-pack$')): handle_service_request,
  265. ('POST', re.compile('/git-receive-pack$')): handle_service_request,
  266. }
  267. def __init__(self, backend, dumb=False, handlers=None):
  268. self.backend = backend
  269. self.dumb = dumb
  270. self.handlers = handlers
  271. def __call__(self, environ, start_response):
  272. path = environ['PATH_INFO']
  273. method = environ['REQUEST_METHOD']
  274. req = HTTPGitRequest(environ, start_response, dumb=self.dumb,
  275. handlers=self.handlers)
  276. # environ['QUERY_STRING'] has qs args
  277. handler = None
  278. for smethod, spath in self.services.iterkeys():
  279. if smethod != method:
  280. continue
  281. mat = spath.search(path)
  282. if mat:
  283. handler = self.services[smethod, spath]
  284. break
  285. if handler is None:
  286. return req.not_found('Sorry, that method is not supported')
  287. return handler(req, self.backend, mat)