web.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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 sys
  23. import time
  24. try:
  25. from urlparse import parse_qs
  26. except ImportError:
  27. from dulwich.misc import parse_qs
  28. from dulwich import log_utils
  29. from dulwich.protocol import (
  30. ReceivableProtocol,
  31. )
  32. from dulwich.repo import (
  33. Repo,
  34. )
  35. from dulwich.server import (
  36. DictBackend,
  37. DEFAULT_HANDLERS,
  38. )
  39. logger = log_utils.getLogger(__name__)
  40. # HTTP error strings
  41. HTTP_OK = '200 OK'
  42. HTTP_NOT_FOUND = '404 Not Found'
  43. HTTP_FORBIDDEN = '403 Forbidden'
  44. HTTP_ERROR = '500 Internal Server Error'
  45. def date_time_string(timestamp=None):
  46. # From BaseHTTPRequestHandler.date_time_string in BaseHTTPServer.py in the
  47. # Python 2.6.5 standard library, following modifications:
  48. # - Made a global rather than an instance method.
  49. # - weekdayname and monthname are renamed and locals rather than class
  50. # variables.
  51. # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved
  52. weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  53. months = [None,
  54. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  55. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  56. if timestamp is None:
  57. timestamp = time.time()
  58. year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
  59. return '%s, %02d %3s %4d %02d:%02d:%02d GMD' % (
  60. weekdays[wd], day, months[month], year, hh, mm, ss)
  61. def url_prefix(mat):
  62. """Extract the URL prefix from a regex match.
  63. :param mat: A regex match object.
  64. :returns: The URL prefix, defined as the text before the match in the
  65. original string. Normalized to start with one leading slash and end with
  66. zero.
  67. """
  68. return '/' + mat.string[:mat.start()].strip('/')
  69. def get_repo(backend, mat):
  70. """Get a Repo instance for the given backend and URL regex match."""
  71. return backend.open_repository(url_prefix(mat))
  72. def send_file(req, f, content_type):
  73. """Send a file-like object to the request output.
  74. :param req: The HTTPGitRequest object to send output to.
  75. :param f: An open file-like object to send; will be closed.
  76. :param content_type: The MIME type for the file.
  77. :return: Iterator over the contents of the file, as chunks.
  78. """
  79. if f is None:
  80. yield req.not_found('File not found')
  81. return
  82. try:
  83. req.respond(HTTP_OK, content_type)
  84. while True:
  85. data = f.read(10240)
  86. if not data:
  87. break
  88. yield data
  89. f.close()
  90. except IOError:
  91. f.close()
  92. yield req.error('Error reading file')
  93. except:
  94. f.close()
  95. raise
  96. def _url_to_path(url):
  97. return url.replace('/', os.path.sep)
  98. def get_text_file(req, backend, mat):
  99. req.nocache()
  100. path = _url_to_path(mat.group())
  101. logger.info('Sending plain text file %s', path)
  102. return send_file(req, get_repo(backend, mat).get_named_file(path),
  103. 'text/plain')
  104. def get_loose_object(req, backend, mat):
  105. sha = mat.group(1) + mat.group(2)
  106. logger.info('Sending loose object %s', sha)
  107. object_store = get_repo(backend, mat).object_store
  108. if not object_store.contains_loose(sha):
  109. yield req.not_found('Object not found')
  110. return
  111. try:
  112. data = object_store[sha].as_legacy_object()
  113. except IOError:
  114. yield req.error('Error reading object')
  115. req.cache_forever()
  116. req.respond(HTTP_OK, 'application/x-git-loose-object')
  117. yield data
  118. def get_pack_file(req, backend, mat):
  119. req.cache_forever()
  120. path = _url_to_path(mat.group())
  121. logger.info('Sending pack file %s', path)
  122. return send_file(req, get_repo(backend, mat).get_named_file(path),
  123. 'application/x-git-packed-objects')
  124. def get_idx_file(req, backend, mat):
  125. req.cache_forever()
  126. path = _url_to_path(mat.group())
  127. logger.info('Sending pack file %s', path)
  128. return send_file(req, get_repo(backend, mat).get_named_file(path),
  129. 'application/x-git-packed-objects-toc')
  130. def get_info_refs(req, backend, mat):
  131. params = parse_qs(req.environ['QUERY_STRING'])
  132. service = params.get('service', [None])[0]
  133. if service and not req.dumb:
  134. handler_cls = req.handlers.get(service, None)
  135. if handler_cls is None:
  136. yield req.forbidden('Unsupported service %s' % service)
  137. return
  138. req.nocache()
  139. write = req.respond(HTTP_OK, 'application/x-%s-advertisement' % service)
  140. proto = ReceivableProtocol(StringIO().read, write)
  141. handler = handler_cls(backend, [url_prefix(mat)], proto,
  142. stateless_rpc=True, advertise_refs=True)
  143. handler.proto.write_pkt_line('# service=%s\n' % service)
  144. handler.proto.write_pkt_line(None)
  145. handler.handle()
  146. else:
  147. # non-smart fallback
  148. # TODO: select_getanyfile() (see http-backend.c)
  149. req.nocache()
  150. req.respond(HTTP_OK, 'text/plain')
  151. logger.info('Emulating dumb info/refs')
  152. repo = get_repo(backend, mat)
  153. refs = repo.get_refs()
  154. for name in sorted(refs.iterkeys()):
  155. # get_refs() includes HEAD as a special case, but we don't want to
  156. # advertise it
  157. if name == 'HEAD':
  158. continue
  159. sha = refs[name]
  160. o = repo[sha]
  161. if not o:
  162. continue
  163. yield '%s\t%s\n' % (sha, name)
  164. peeled_sha = repo.get_peeled(name)
  165. if peeled_sha != sha:
  166. yield '%s\t%s^{}\n' % (peeled_sha, name)
  167. def get_info_packs(req, backend, mat):
  168. req.nocache()
  169. req.respond(HTTP_OK, 'text/plain')
  170. logger.info('Emulating dumb info/packs')
  171. for pack in get_repo(backend, mat).object_store.packs:
  172. yield 'P pack-%s.pack\n' % pack.name()
  173. class _LengthLimitedFile(object):
  174. """Wrapper class to limit the length of reads from a file-like object.
  175. This is used to ensure EOF is read from the wsgi.input object once
  176. Content-Length bytes are read. This behavior is required by the WSGI spec
  177. but not implemented in wsgiref as of 2.5.
  178. """
  179. def __init__(self, input, max_bytes):
  180. self._input = input
  181. self._bytes_avail = max_bytes
  182. def read(self, size=-1):
  183. if self._bytes_avail <= 0:
  184. return ''
  185. if size == -1 or size > self._bytes_avail:
  186. size = self._bytes_avail
  187. self._bytes_avail -= size
  188. return self._input.read(size)
  189. # TODO: support more methods as necessary
  190. def handle_service_request(req, backend, mat):
  191. service = mat.group().lstrip('/')
  192. logger.info('Handling service request for %s', service)
  193. handler_cls = req.handlers.get(service, None)
  194. if handler_cls is None:
  195. yield req.forbidden('Unsupported service %s' % service)
  196. return
  197. req.nocache()
  198. write = req.respond(HTTP_OK, 'application/x-%s-response' % service)
  199. input = req.environ['wsgi.input']
  200. # This is not necessary if this app is run from a conforming WSGI server.
  201. # Unfortunately, there's no way to tell that at this point.
  202. # TODO: git may used HTTP/1.1 chunked encoding instead of specifying
  203. # content-length
  204. content_length = req.environ.get('CONTENT_LENGTH', '')
  205. if content_length:
  206. input = _LengthLimitedFile(input, int(content_length))
  207. proto = ReceivableProtocol(input.read, write)
  208. handler = handler_cls(backend, [url_prefix(mat)], proto, stateless_rpc=True)
  209. handler.handle()
  210. class HTTPGitRequest(object):
  211. """Class encapsulating the state of a single git HTTP request.
  212. :ivar environ: the WSGI environment for the request.
  213. """
  214. def __init__(self, environ, start_response, dumb=False, handlers=None):
  215. self.environ = environ
  216. self.dumb = dumb
  217. self.handlers = handlers and handlers or DEFAULT_HANDLERS
  218. self._start_response = start_response
  219. self._cache_headers = []
  220. self._headers = []
  221. def add_header(self, name, value):
  222. """Add a header to the response."""
  223. self._headers.append((name, value))
  224. def respond(self, status=HTTP_OK, content_type=None, headers=None):
  225. """Begin a response with the given status and other headers."""
  226. if headers:
  227. self._headers.extend(headers)
  228. if content_type:
  229. self._headers.append(('Content-Type', content_type))
  230. self._headers.extend(self._cache_headers)
  231. return self._start_response(status, self._headers)
  232. def not_found(self, message):
  233. """Begin a HTTP 404 response and return the text of a message."""
  234. self._cache_headers = []
  235. logger.info('Not found: %s', message)
  236. self.respond(HTTP_NOT_FOUND, 'text/plain')
  237. return message
  238. def forbidden(self, message):
  239. """Begin a HTTP 403 response and return the text of a message."""
  240. self._cache_headers = []
  241. logger.info('Forbidden: %s', message)
  242. self.respond(HTTP_FORBIDDEN, 'text/plain')
  243. return message
  244. def error(self, message):
  245. """Begin a HTTP 500 response and return the text of a message."""
  246. self._cache_headers = []
  247. logger.error('Error: %s', message)
  248. self.respond(HTTP_ERROR, 'text/plain')
  249. return message
  250. def nocache(self):
  251. """Set the response to never be cached by the client."""
  252. self._cache_headers = [
  253. ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'),
  254. ('Pragma', 'no-cache'),
  255. ('Cache-Control', 'no-cache, max-age=0, must-revalidate'),
  256. ]
  257. def cache_forever(self):
  258. """Set the response to be cached forever by the client."""
  259. now = time.time()
  260. self._cache_headers = [
  261. ('Date', date_time_string(now)),
  262. ('Expires', date_time_string(now + 31536000)),
  263. ('Cache-Control', 'public, max-age=31536000'),
  264. ]
  265. class HTTPGitApplication(object):
  266. """Class encapsulating the state of a git WSGI application.
  267. :ivar backend: the Backend object backing this application
  268. """
  269. services = {
  270. ('GET', re.compile('/HEAD$')): get_text_file,
  271. ('GET', re.compile('/info/refs$')): get_info_refs,
  272. ('GET', re.compile('/objects/info/alternates$')): get_text_file,
  273. ('GET', re.compile('/objects/info/http-alternates$')): get_text_file,
  274. ('GET', re.compile('/objects/info/packs$')): get_info_packs,
  275. ('GET', re.compile('/objects/([0-9a-f]{2})/([0-9a-f]{38})$')): get_loose_object,
  276. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.pack$')): get_pack_file,
  277. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.idx$')): get_idx_file,
  278. ('POST', re.compile('/git-upload-pack$')): handle_service_request,
  279. ('POST', re.compile('/git-receive-pack$')): handle_service_request,
  280. }
  281. def __init__(self, backend, dumb=False, handlers=None):
  282. self.backend = backend
  283. self.dumb = dumb
  284. self.handlers = handlers
  285. def __call__(self, environ, start_response):
  286. path = environ['PATH_INFO']
  287. method = environ['REQUEST_METHOD']
  288. req = HTTPGitRequest(environ, start_response, dumb=self.dumb,
  289. handlers=self.handlers)
  290. # environ['QUERY_STRING'] has qs args
  291. handler = None
  292. for smethod, spath in self.services.iterkeys():
  293. if smethod != method:
  294. continue
  295. mat = spath.search(path)
  296. if mat:
  297. handler = self.services[smethod, spath]
  298. break
  299. if handler is None:
  300. return req.not_found('Sorry, that method is not supported')
  301. return handler(req, self.backend, mat)
  302. # The reference server implementation is based on wsgiref, which is not
  303. # distributed with python 2.4. If wsgiref is not present, users will not be able
  304. # to use the HTTP server without a little extra work.
  305. try:
  306. from wsgiref.simple_server import (
  307. WSGIRequestHandler,
  308. make_server,
  309. )
  310. class HTTPGitRequestHandler(WSGIRequestHandler):
  311. """Handler that uses dulwich's logger for logging exceptions."""
  312. def log_exception(self, exc_info):
  313. logger.exception('Exception happened during processing of request',
  314. exc_info=exc_info)
  315. def log_message(self, format, *args):
  316. logger.info(format, *args)
  317. def log_error(self, *args):
  318. logger.error(*args)
  319. def main(argv=sys.argv):
  320. """Entry point for starting an HTTP git server."""
  321. if len(argv) > 1:
  322. gitdir = argv[1]
  323. else:
  324. gitdir = os.getcwd()
  325. # TODO: allow serving on other addresses/ports via command-line flag
  326. listen_addr=''
  327. port = 8000
  328. log_utils.default_logging_config()
  329. backend = DictBackend({'/': Repo(gitdir)})
  330. app = HTTPGitApplication(backend)
  331. server = make_server(listen_addr, port, app,
  332. handler_class=HTTPGitRequestHandler)
  333. logger.info('Listening for HTTP connections on %s:%d', listen_addr,
  334. port)
  335. server.serve_forever()
  336. except ImportError:
  337. # No wsgiref found; don't provide the reference functionality, but leave the
  338. # rest of the WSGI-based implementation.
  339. def main(argv=sys.argv):
  340. """Stub entry point for failing to start a server without wsgiref."""
  341. sys.stderr.write('Sorry, the wsgiref module is required for dul-web.\n')
  342. sys.exit(1)