web.py 11 KB

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