2
0

web.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. # web.py -- WSGI smart-http server
  2. # Copryight (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 re
  21. import time
  22. try:
  23. from urlparse import parse_qs
  24. except ImportError:
  25. from dulwich.misc import parse_qs
  26. from dulwich.server import (
  27. ReceivePackHandler,
  28. UploadPackHandler,
  29. )
  30. HTTP_OK = '200 OK'
  31. HTTP_NOT_FOUND = '404 Not Found'
  32. HTTP_FORBIDDEN = '403 Forbidden'
  33. def date_time_string(timestamp=None):
  34. # Based on BaseHTTPServer.py in python2.5
  35. weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  36. months = [None,
  37. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  38. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  39. if timestamp is None:
  40. timestamp = time.time()
  41. year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
  42. return '%s, %02d %3s %4d %02d:%02d:%02d GMD' % (
  43. weekdays[wd], day, months[month], year, hh, mm, ss)
  44. def url_prefix(mat):
  45. """Extract the URL prefix from a regex match.
  46. :param mat: A regex match object.
  47. :returns: The URL prefix, defined as the text before the match in the
  48. original string. Normalized to start with one leading slash and end with
  49. zero.
  50. """
  51. return '/' + mat.string[:mat.start()].strip('/')
  52. def get_repo(backend, mat):
  53. """Get a Repo instance for the given backend and URL regex match."""
  54. return backend.open_repository(url_prefix(mat))
  55. def send_file(req, f, content_type):
  56. """Send a file-like object to the request output.
  57. :param req: The HTTPGitRequest object to send output to.
  58. :param f: An open file-like object to send; will be closed.
  59. :param content_type: The MIME type for the file.
  60. :yield: The contents of the file.
  61. """
  62. if f is None:
  63. yield req.not_found('File not found')
  64. return
  65. try:
  66. try:
  67. req.respond(HTTP_OK, content_type)
  68. while True:
  69. data = f.read(10240)
  70. if not data:
  71. break
  72. yield data
  73. except IOError:
  74. yield req.not_found('Error reading file')
  75. finally:
  76. f.close()
  77. def get_text_file(req, backend, mat):
  78. req.nocache()
  79. return send_file(req, get_repo(backend, mat).get_named_file(mat.group()),
  80. 'text/plain')
  81. def get_loose_object(req, backend, mat):
  82. sha = mat.group(1) + mat.group(2)
  83. object_store = get_repo(backend, mat).object_store
  84. if not object_store.contains_loose(sha):
  85. yield req.not_found('Object not found')
  86. return
  87. try:
  88. data = object_store[sha].as_legacy_object()
  89. except IOError:
  90. yield req.not_found('Error reading object')
  91. req.cache_forever()
  92. req.respond(HTTP_OK, 'application/x-git-loose-object')
  93. yield data
  94. def get_pack_file(req, backend, mat):
  95. req.cache_forever()
  96. return send_file(req, get_repo(backend, mat).get_named_file(mat.group()),
  97. 'application/x-git-packed-objects')
  98. def get_idx_file(req, backend, mat):
  99. req.cache_forever()
  100. return send_file(req, get_repo(backend, mat).get_named_file(mat.group()),
  101. 'application/x-git-packed-objects-toc')
  102. default_services = {'git-upload-pack': UploadPackHandler,
  103. 'git-receive-pack': ReceivePackHandler}
  104. def get_info_refs(req, backend, mat, services=None):
  105. if services is None:
  106. services = default_services
  107. params = parse_qs(req.environ['QUERY_STRING'])
  108. service = params.get('service', [None])[0]
  109. if service and not req.dumb:
  110. handler_cls = services.get(service, None)
  111. if handler_cls is None:
  112. yield req.forbidden('Unsupported service %s' % service)
  113. return
  114. req.nocache()
  115. req.respond(HTTP_OK, 'application/x-%s-advertisement' % service)
  116. output = StringIO()
  117. dummy_input = StringIO() # GET request, handler doesn't need to read
  118. handler = handler_cls(backend, [url_prefix(mat)],
  119. dummy_input.read, output.write,
  120. stateless_rpc=True, advertise_refs=True)
  121. handler.proto.write_pkt_line('# service=%s\n' % service)
  122. handler.proto.write_pkt_line(None)
  123. handler.handle()
  124. yield output.getvalue()
  125. else:
  126. # non-smart fallback
  127. # TODO: select_getanyfile() (see http-backend.c)
  128. req.nocache()
  129. req.respond(HTTP_OK, 'text/plain')
  130. repo = get_repo(backend, mat)
  131. refs = repo.get_refs()
  132. for name in sorted(refs.iterkeys()):
  133. # get_refs() includes HEAD as a special case, but we don't want to
  134. # advertise it
  135. if name == 'HEAD':
  136. continue
  137. sha = refs[name]
  138. o = repo[sha]
  139. if not o:
  140. continue
  141. yield '%s\t%s\n' % (sha, name)
  142. peeled_sha = repo.get_peeled(name)
  143. if peeled_sha != sha:
  144. yield '%s\t%s^{}\n' % (peeled_sha, name)
  145. def get_info_packs(req, backend, mat):
  146. req.nocache()
  147. req.respond(HTTP_OK, 'text/plain')
  148. for pack in get_repo(backend, mat).object_store.packs:
  149. yield 'P pack-%s.pack\n' % pack.name()
  150. class _LengthLimitedFile(object):
  151. """Wrapper class to limit the length of reads from a file-like object.
  152. This is used to ensure EOF is read from the wsgi.input object once
  153. Content-Length bytes are read. This behavior is required by the WSGI spec
  154. but not implemented in wsgiref as of 2.5.
  155. """
  156. def __init__(self, input, max_bytes):
  157. self._input = input
  158. self._bytes_avail = max_bytes
  159. def read(self, size=-1):
  160. if self._bytes_avail <= 0:
  161. return ''
  162. if size == -1 or size > self._bytes_avail:
  163. size = self._bytes_avail
  164. self._bytes_avail -= size
  165. return self._input.read(size)
  166. # TODO: support more methods as necessary
  167. def handle_service_request(req, backend, mat, services=None):
  168. if services is None:
  169. services = default_services
  170. service = mat.group().lstrip('/')
  171. handler_cls = services.get(service, None)
  172. if handler_cls is None:
  173. yield req.forbidden('Unsupported service %s' % service)
  174. return
  175. req.nocache()
  176. req.respond(HTTP_OK, 'application/x-%s-response' % service)
  177. output = StringIO()
  178. input = req.environ['wsgi.input']
  179. # This is not necessary if this app is run from a conforming WSGI server.
  180. # Unfortunately, there's no way to tell that at this point.
  181. # TODO: git may used HTTP/1.1 chunked encoding instead of specifying
  182. # content-length
  183. if 'CONTENT_LENGTH' in req.environ:
  184. input = _LengthLimitedFile(input, int(req.environ['CONTENT_LENGTH']))
  185. handler = handler_cls(backend, [url_prefix(mat)], input.read, output.write,
  186. stateless_rpc=True)
  187. handler.handle()
  188. yield output.getvalue()
  189. class HTTPGitRequest(object):
  190. """Class encapsulating the state of a single git HTTP request.
  191. :ivar environ: the WSGI environment for the request.
  192. """
  193. def __init__(self, environ, start_response, dumb=False):
  194. self.environ = environ
  195. self.dumb = dumb
  196. self._start_response = start_response
  197. self._cache_headers = []
  198. self._headers = []
  199. def add_header(self, name, value):
  200. """Add a header to the response."""
  201. self._headers.append((name, value))
  202. def respond(self, status=HTTP_OK, content_type=None, headers=None):
  203. """Begin a response with the given status and other headers."""
  204. if headers:
  205. self._headers.extend(headers)
  206. if content_type:
  207. self._headers.append(('Content-Type', content_type))
  208. self._headers.extend(self._cache_headers)
  209. self._start_response(status, self._headers)
  210. def not_found(self, message):
  211. """Begin a HTTP 404 response and return the text of a message."""
  212. self._cache_headers = []
  213. self.respond(HTTP_NOT_FOUND, 'text/plain')
  214. return message
  215. def forbidden(self, message):
  216. """Begin a HTTP 403 response and return the text of a message."""
  217. self._cache_headers = []
  218. self.respond(HTTP_FORBIDDEN, 'text/plain')
  219. return message
  220. def nocache(self):
  221. """Set the response to never be cached by the client."""
  222. self._cache_headers = [
  223. ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'),
  224. ('Pragma', 'no-cache'),
  225. ('Cache-Control', 'no-cache, max-age=0, must-revalidate'),
  226. ]
  227. def cache_forever(self):
  228. """Set the response to be cached forever by the client."""
  229. now = time.time()
  230. self._cache_headers = [
  231. ('Date', date_time_string(now)),
  232. ('Expires', date_time_string(now + 31536000)),
  233. ('Cache-Control', 'public, max-age=31536000'),
  234. ]
  235. class HTTPGitApplication(object):
  236. """Class encapsulating the state of a git WSGI application.
  237. :ivar backend: the Backend object backing this application
  238. """
  239. services = {
  240. ('GET', re.compile('/HEAD$')): get_text_file,
  241. ('GET', re.compile('/info/refs$')): get_info_refs,
  242. ('GET', re.compile('/objects/info/alternates$')): get_text_file,
  243. ('GET', re.compile('/objects/info/http-alternates$')): get_text_file,
  244. ('GET', re.compile('/objects/info/packs$')): get_info_packs,
  245. ('GET', re.compile('/objects/([0-9a-f]{2})/([0-9a-f]{38})$')): get_loose_object,
  246. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.pack$')): get_pack_file,
  247. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.idx$')): get_idx_file,
  248. ('POST', re.compile('/git-upload-pack$')): handle_service_request,
  249. ('POST', re.compile('/git-receive-pack$')): handle_service_request,
  250. }
  251. def __init__(self, backend, dumb=False):
  252. self.backend = backend
  253. self.dumb = dumb
  254. def __call__(self, environ, start_response):
  255. path = environ['PATH_INFO']
  256. method = environ['REQUEST_METHOD']
  257. req = HTTPGitRequest(environ, start_response, self.dumb)
  258. # environ['QUERY_STRING'] has qs args
  259. handler = None
  260. for smethod, spath in self.services.iterkeys():
  261. if smethod != method:
  262. continue
  263. mat = spath.search(path)
  264. if mat:
  265. handler = self.services[smethod, spath]
  266. break
  267. if handler is None:
  268. return req.not_found('Sorry, that method is not supported')
  269. return handler(req, self.backend, mat)