web.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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.protocol import (
  28. ReceivableProtocol,
  29. )
  30. from dulwich.server import (
  31. ReceivePackHandler,
  32. UploadPackHandler,
  33. DEFAULT_HANDLERS,
  34. )
  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. return send_file(req, get_repo(backend, mat).get_named_file(path),
  91. 'text/plain')
  92. def get_loose_object(req, backend, mat):
  93. sha = mat.group(1) + mat.group(2)
  94. object_store = get_repo(backend, mat).object_store
  95. if not object_store.contains_loose(sha):
  96. yield req.not_found('Object not found')
  97. return
  98. try:
  99. data = object_store[sha].as_legacy_object()
  100. except IOError:
  101. yield req.not_found('Error reading object')
  102. req.cache_forever()
  103. req.respond(HTTP_OK, 'application/x-git-loose-object')
  104. yield data
  105. def get_pack_file(req, backend, mat):
  106. req.cache_forever()
  107. path = _url_to_path(mat.group())
  108. return send_file(req, get_repo(backend, mat).get_named_file(path),
  109. 'application/x-git-packed-objects')
  110. def get_idx_file(req, backend, mat):
  111. req.cache_forever()
  112. path = _url_to_path(mat.group())
  113. return send_file(req, get_repo(backend, mat).get_named_file(path),
  114. 'application/x-git-packed-objects-toc')
  115. def get_info_refs(req, backend, mat):
  116. params = parse_qs(req.environ['QUERY_STRING'])
  117. service = params.get('service', [None])[0]
  118. if service and not req.dumb:
  119. handler_cls = req.handlers.get(service, None)
  120. if handler_cls is None:
  121. yield req.forbidden('Unsupported service %s' % service)
  122. return
  123. req.nocache()
  124. req.respond(HTTP_OK, 'application/x-%s-advertisement' % service)
  125. output = StringIO()
  126. proto = ReceivableProtocol(StringIO().read, output.write)
  127. handler = handler_cls(backend, [url_prefix(mat)], proto,
  128. stateless_rpc=True, advertise_refs=True)
  129. handler.proto.write_pkt_line('# service=%s\n' % service)
  130. handler.proto.write_pkt_line(None)
  131. handler.handle()
  132. yield output.getvalue()
  133. else:
  134. # non-smart fallback
  135. # TODO: select_getanyfile() (see http-backend.c)
  136. req.nocache()
  137. req.respond(HTTP_OK, 'text/plain')
  138. repo = get_repo(backend, mat)
  139. refs = repo.get_refs()
  140. for name in sorted(refs.iterkeys()):
  141. # get_refs() includes HEAD as a special case, but we don't want to
  142. # advertise it
  143. if name == 'HEAD':
  144. continue
  145. sha = refs[name]
  146. o = repo[sha]
  147. if not o:
  148. continue
  149. yield '%s\t%s\n' % (sha, name)
  150. peeled_sha = repo.get_peeled(name)
  151. if peeled_sha != sha:
  152. yield '%s\t%s^{}\n' % (peeled_sha, name)
  153. def get_info_packs(req, backend, mat):
  154. req.nocache()
  155. req.respond(HTTP_OK, 'text/plain')
  156. for pack in get_repo(backend, mat).object_store.packs:
  157. yield 'P pack-%s.pack\n' % pack.name()
  158. class _LengthLimitedFile(object):
  159. """Wrapper class to limit the length of reads from a file-like object.
  160. This is used to ensure EOF is read from the wsgi.input object once
  161. Content-Length bytes are read. This behavior is required by the WSGI spec
  162. but not implemented in wsgiref as of 2.5.
  163. """
  164. def __init__(self, input, max_bytes):
  165. self._input = input
  166. self._bytes_avail = max_bytes
  167. def read(self, size=-1):
  168. if self._bytes_avail <= 0:
  169. return ''
  170. if size == -1 or size > self._bytes_avail:
  171. size = self._bytes_avail
  172. self._bytes_avail -= size
  173. return self._input.read(size)
  174. # TODO: support more methods as necessary
  175. def handle_service_request(req, backend, mat):
  176. service = mat.group().lstrip('/')
  177. handler_cls = req.handlers.get(service, None)
  178. if handler_cls is None:
  179. yield req.forbidden('Unsupported service %s' % service)
  180. return
  181. req.nocache()
  182. req.respond(HTTP_OK, 'application/x-%s-response' % service)
  183. output = StringIO()
  184. input = req.environ['wsgi.input']
  185. # This is not necessary if this app is run from a conforming WSGI server.
  186. # Unfortunately, there's no way to tell that at this point.
  187. # TODO: git may used HTTP/1.1 chunked encoding instead of specifying
  188. # content-length
  189. if 'CONTENT_LENGTH' in req.environ:
  190. input = _LengthLimitedFile(input, int(req.environ['CONTENT_LENGTH']))
  191. proto = ReceivableProtocol(input.read, output.write)
  192. handler = handler_cls(backend, [url_prefix(mat)], proto, stateless_rpc=True)
  193. handler.handle()
  194. yield output.getvalue()
  195. class HTTPGitRequest(object):
  196. """Class encapsulating the state of a single git HTTP request.
  197. :ivar environ: the WSGI environment for the request.
  198. """
  199. def __init__(self, environ, start_response, dumb=False, handlers=None):
  200. self.environ = environ
  201. self.dumb = dumb
  202. self.handlers = handlers and handlers or DEFAULT_HANDLERS
  203. self._start_response = start_response
  204. self._cache_headers = []
  205. self._headers = []
  206. def add_header(self, name, value):
  207. """Add a header to the response."""
  208. self._headers.append((name, value))
  209. def respond(self, status=HTTP_OK, content_type=None, headers=None):
  210. """Begin a response with the given status and other headers."""
  211. if headers:
  212. self._headers.extend(headers)
  213. if content_type:
  214. self._headers.append(('Content-Type', content_type))
  215. self._headers.extend(self._cache_headers)
  216. self._start_response(status, self._headers)
  217. def not_found(self, message):
  218. """Begin a HTTP 404 response and return the text of a message."""
  219. self._cache_headers = []
  220. self.respond(HTTP_NOT_FOUND, 'text/plain')
  221. return message
  222. def forbidden(self, message):
  223. """Begin a HTTP 403 response and return the text of a message."""
  224. self._cache_headers = []
  225. self.respond(HTTP_FORBIDDEN, 'text/plain')
  226. return message
  227. def nocache(self):
  228. """Set the response to never be cached by the client."""
  229. self._cache_headers = [
  230. ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'),
  231. ('Pragma', 'no-cache'),
  232. ('Cache-Control', 'no-cache, max-age=0, must-revalidate'),
  233. ]
  234. def cache_forever(self):
  235. """Set the response to be cached forever by the client."""
  236. now = time.time()
  237. self._cache_headers = [
  238. ('Date', date_time_string(now)),
  239. ('Expires', date_time_string(now + 31536000)),
  240. ('Cache-Control', 'public, max-age=31536000'),
  241. ]
  242. class HTTPGitApplication(object):
  243. """Class encapsulating the state of a git WSGI application.
  244. :ivar backend: the Backend object backing this application
  245. """
  246. services = {
  247. ('GET', re.compile('/HEAD$')): get_text_file,
  248. ('GET', re.compile('/info/refs$')): get_info_refs,
  249. ('GET', re.compile('/objects/info/alternates$')): get_text_file,
  250. ('GET', re.compile('/objects/info/http-alternates$')): get_text_file,
  251. ('GET', re.compile('/objects/info/packs$')): get_info_packs,
  252. ('GET', re.compile('/objects/([0-9a-f]{2})/([0-9a-f]{38})$')): get_loose_object,
  253. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.pack$')): get_pack_file,
  254. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.idx$')): get_idx_file,
  255. ('POST', re.compile('/git-upload-pack$')): handle_service_request,
  256. ('POST', re.compile('/git-receive-pack$')): handle_service_request,
  257. }
  258. def __init__(self, backend, dumb=False, handlers=None):
  259. self.backend = backend
  260. self.dumb = dumb
  261. self.handlers = handlers
  262. def __call__(self, environ, start_response):
  263. path = environ['PATH_INFO']
  264. method = environ['REQUEST_METHOD']
  265. req = HTTPGitRequest(environ, start_response, dumb=self.dumb,
  266. handlers=self.handlers)
  267. # environ['QUERY_STRING'] has qs args
  268. handler = None
  269. for smethod, spath in self.services.iterkeys():
  270. if smethod != method:
  271. continue
  272. mat = spath.search(path)
  273. if mat:
  274. handler = self.services[smethod, spath]
  275. break
  276. if handler is None:
  277. return req.not_found('Sorry, that method is not supported')
  278. return handler(req, self.backend, mat)