web.py 11 KB

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