web.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. # web.py -- WSGI smart-http server
  2. # Copyright (C) 2010 Google, Inc.
  3. # Copyright (C) 2012 Jelmer Vernooij <jelmer@jelmer.uk>
  4. #
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """HTTP server for dulwich that implements the git smart HTTP protocol."""
  22. from io import BytesIO
  23. import shutil
  24. import tempfile
  25. import gzip
  26. import os
  27. import re
  28. import sys
  29. import time
  30. from typing import List, Tuple, Optional
  31. from wsgiref.simple_server import (
  32. WSGIRequestHandler,
  33. ServerHandler,
  34. WSGIServer,
  35. make_server,
  36. )
  37. from urllib.parse import parse_qs
  38. from dulwich import log_utils
  39. from dulwich.protocol import (
  40. ReceivableProtocol,
  41. )
  42. from dulwich.repo import (
  43. BaseRepo,
  44. NotGitRepository,
  45. Repo,
  46. )
  47. from dulwich.server import (
  48. DictBackend,
  49. DEFAULT_HANDLERS,
  50. generate_info_refs,
  51. generate_objects_info_packs,
  52. )
  53. logger = log_utils.getLogger(__name__)
  54. # HTTP error strings
  55. HTTP_OK = '200 OK'
  56. HTTP_NOT_FOUND = '404 Not Found'
  57. HTTP_FORBIDDEN = '403 Forbidden'
  58. HTTP_ERROR = '500 Internal Server Error'
  59. def date_time_string(timestamp: Optional[float] = None) -> str:
  60. # From BaseHTTPRequestHandler.date_time_string in BaseHTTPServer.py in the
  61. # Python 2.6.5 standard library, following modifications:
  62. # - Made a global rather than an instance method.
  63. # - weekdayname and monthname are renamed and locals rather than class
  64. # variables.
  65. # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved
  66. weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  67. months = [None,
  68. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  69. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  70. if timestamp is None:
  71. timestamp = time.time()
  72. year, month, day, hh, mm, ss, wd = time.gmtime(timestamp)[:7]
  73. return '%s, %02d %3s %4d %02d:%02d:%02d GMD' % (
  74. weekdays[wd], day, months[month], year, hh, mm, ss)
  75. def url_prefix(mat) -> str:
  76. """Extract the URL prefix from a regex match.
  77. Args:
  78. mat: A regex match object.
  79. Returns: The URL prefix, defined as the text before the match in the
  80. original string. Normalized to start with one leading slash and end
  81. with zero.
  82. """
  83. return '/' + mat.string[:mat.start()].strip('/')
  84. def get_repo(backend, mat) -> BaseRepo:
  85. """Get a Repo instance for the given backend and URL regex match."""
  86. return backend.open_repository(url_prefix(mat))
  87. def send_file(req, f, content_type):
  88. """Send a file-like object to the request output.
  89. Args:
  90. req: The HTTPGitRequest object to send output to.
  91. f: An open file-like object to send; will be closed.
  92. content_type: The MIME type for the file.
  93. Returns: Iterator over the contents of the file, as chunks.
  94. """
  95. if f is None:
  96. yield req.not_found('File not found')
  97. return
  98. try:
  99. req.respond(HTTP_OK, content_type)
  100. while True:
  101. data = f.read(10240)
  102. if not data:
  103. break
  104. yield data
  105. except IOError:
  106. yield req.error('Error reading file')
  107. finally:
  108. f.close()
  109. def _url_to_path(url):
  110. return url.replace('/', os.path.sep)
  111. def get_text_file(req, backend, mat):
  112. req.nocache()
  113. path = _url_to_path(mat.group())
  114. logger.info('Sending plain text file %s', path)
  115. return send_file(req, get_repo(backend, mat).get_named_file(path),
  116. 'text/plain')
  117. def get_loose_object(req, backend, mat):
  118. sha = (mat.group(1) + mat.group(2)).encode('ascii')
  119. logger.info('Sending loose object %s', sha)
  120. object_store = get_repo(backend, mat).object_store
  121. if not object_store.contains_loose(sha):
  122. yield req.not_found('Object not found')
  123. return
  124. try:
  125. data = object_store[sha].as_legacy_object()
  126. except IOError:
  127. yield req.error('Error reading object')
  128. return
  129. req.cache_forever()
  130. req.respond(HTTP_OK, 'application/x-git-loose-object')
  131. yield data
  132. def get_pack_file(req, backend, mat):
  133. req.cache_forever()
  134. path = _url_to_path(mat.group())
  135. logger.info('Sending pack file %s', path)
  136. return send_file(req, get_repo(backend, mat).get_named_file(path),
  137. 'application/x-git-packed-objects')
  138. def get_idx_file(req, backend, mat):
  139. req.cache_forever()
  140. path = _url_to_path(mat.group())
  141. logger.info('Sending pack file %s', path)
  142. return send_file(req, get_repo(backend, mat).get_named_file(path),
  143. 'application/x-git-packed-objects-toc')
  144. def get_info_refs(req, backend, mat):
  145. params = parse_qs(req.environ['QUERY_STRING'])
  146. service = params.get('service', [None])[0]
  147. try:
  148. repo = get_repo(backend, mat)
  149. except NotGitRepository as e:
  150. yield req.not_found(str(e))
  151. return
  152. if service and not req.dumb:
  153. handler_cls = req.handlers.get(service.encode('ascii'), None)
  154. if handler_cls is None:
  155. yield req.forbidden('Unsupported service')
  156. return
  157. req.nocache()
  158. write = req.respond(
  159. HTTP_OK, 'application/x-%s-advertisement' % service)
  160. proto = ReceivableProtocol(BytesIO().read, write)
  161. handler = handler_cls(backend, [url_prefix(mat)], proto,
  162. http_req=req, advertise_refs=True)
  163. handler.proto.write_pkt_line(
  164. b'# service=' + service.encode('ascii') + b'\n')
  165. handler.proto.write_pkt_line(None)
  166. handler.handle()
  167. else:
  168. # non-smart fallback
  169. # TODO: select_getanyfile() (see http-backend.c)
  170. req.nocache()
  171. req.respond(HTTP_OK, 'text/plain')
  172. logger.info('Emulating dumb info/refs')
  173. for text in generate_info_refs(repo):
  174. yield text
  175. def get_info_packs(req, backend, mat):
  176. req.nocache()
  177. req.respond(HTTP_OK, 'text/plain')
  178. logger.info('Emulating dumb info/packs')
  179. return generate_objects_info_packs(get_repo(backend, mat))
  180. class _LengthLimitedFile(object):
  181. """Wrapper class to limit the length of reads from a file-like object.
  182. This is used to ensure EOF is read from the wsgi.input object once
  183. Content-Length bytes are read. This behavior is required by the WSGI spec
  184. but not implemented in wsgiref as of 2.5.
  185. """
  186. def __init__(self, input, max_bytes):
  187. self._input = input
  188. self._bytes_avail = max_bytes
  189. def read(self, size=-1):
  190. if self._bytes_avail <= 0:
  191. return b''
  192. if size == -1 or size > self._bytes_avail:
  193. size = self._bytes_avail
  194. self._bytes_avail -= size
  195. return self._input.read(size)
  196. # TODO: support more methods as necessary
  197. def handle_service_request(req, backend, mat):
  198. service = mat.group().lstrip('/')
  199. logger.info('Handling service request for %s', service)
  200. handler_cls = req.handlers.get(service.encode('ascii'), None)
  201. if handler_cls is None:
  202. yield req.forbidden('Unsupported service')
  203. return
  204. try:
  205. get_repo(backend, mat)
  206. except NotGitRepository as e:
  207. yield req.not_found(str(e))
  208. return
  209. req.nocache()
  210. write = req.respond(HTTP_OK, 'application/x-%s-result' % service)
  211. proto = ReceivableProtocol(req.environ['wsgi.input'].read, write)
  212. # TODO(jelmer): Find a way to pass in repo, rather than having handler_cls
  213. # reopen.
  214. handler = handler_cls(backend, [url_prefix(mat)], proto, http_req=req)
  215. handler.handle()
  216. class HTTPGitRequest(object):
  217. """Class encapsulating the state of a single git HTTP request.
  218. :ivar environ: the WSGI environment for the request.
  219. """
  220. def __init__(
  221. self, environ, start_response, dumb: bool = False, handlers=None):
  222. self.environ = environ
  223. self.dumb = dumb
  224. self.handlers = handlers
  225. self._start_response = start_response
  226. self._cache_headers = [] # type: List[Tuple[str, str]]
  227. self._headers = [] # type: List[Tuple[str, str]]
  228. def add_header(self, name, value):
  229. """Add a header to the response."""
  230. self._headers.append((name, value))
  231. def respond(
  232. self, status: str = HTTP_OK,
  233. content_type: Optional[str] = None,
  234. headers: Optional[List[Tuple[str, str]]] = None):
  235. """Begin a response with the given status and other headers."""
  236. if headers:
  237. self._headers.extend(headers)
  238. if content_type:
  239. self._headers.append(('Content-Type', content_type))
  240. self._headers.extend(self._cache_headers)
  241. return self._start_response(status, self._headers)
  242. def not_found(self, message: str) -> bytes:
  243. """Begin a HTTP 404 response and return the text of a message."""
  244. self._cache_headers = []
  245. logger.info('Not found: %s', message)
  246. self.respond(HTTP_NOT_FOUND, 'text/plain')
  247. return message.encode('ascii')
  248. def forbidden(self, message: str) -> bytes:
  249. """Begin a HTTP 403 response and return the text of a message."""
  250. self._cache_headers = []
  251. logger.info('Forbidden: %s', message)
  252. self.respond(HTTP_FORBIDDEN, 'text/plain')
  253. return message.encode('ascii')
  254. def error(self, message: str) -> bytes:
  255. """Begin a HTTP 500 response and return the text of a message."""
  256. self._cache_headers = []
  257. logger.error('Error: %s', message)
  258. self.respond(HTTP_ERROR, 'text/plain')
  259. return message.encode('ascii')
  260. def nocache(self) -> None:
  261. """Set the response to never be cached by the client."""
  262. self._cache_headers = [
  263. ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'),
  264. ('Pragma', 'no-cache'),
  265. ('Cache-Control', 'no-cache, max-age=0, must-revalidate'),
  266. ]
  267. def cache_forever(self) -> None:
  268. """Set the response to be cached forever by the client."""
  269. now = time.time()
  270. self._cache_headers = [
  271. ('Date', date_time_string(now)),
  272. ('Expires', date_time_string(now + 31536000)),
  273. ('Cache-Control', 'public, max-age=31536000'),
  274. ]
  275. class HTTPGitApplication(object):
  276. """Class encapsulating the state of a git WSGI application.
  277. :ivar backend: the Backend object backing this application
  278. """
  279. services = {
  280. ('GET', re.compile('/HEAD$')): get_text_file,
  281. ('GET', re.compile('/info/refs$')): get_info_refs,
  282. ('GET', re.compile('/objects/info/alternates$')): get_text_file,
  283. ('GET', re.compile('/objects/info/http-alternates$')): get_text_file,
  284. ('GET', re.compile('/objects/info/packs$')): get_info_packs,
  285. ('GET', re.compile('/objects/([0-9a-f]{2})/([0-9a-f]{38})$')):
  286. get_loose_object,
  287. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.pack$')):
  288. get_pack_file,
  289. ('GET', re.compile('/objects/pack/pack-([0-9a-f]{40})\\.idx$')):
  290. get_idx_file,
  291. ('POST', re.compile('/git-upload-pack$')): handle_service_request,
  292. ('POST', re.compile('/git-receive-pack$')): handle_service_request,
  293. }
  294. def __init__(
  295. self, backend, dumb: bool = False, handlers=None,
  296. fallback_app=None):
  297. self.backend = backend
  298. self.dumb = dumb
  299. self.handlers = dict(DEFAULT_HANDLERS)
  300. self.fallback_app = fallback_app
  301. if handlers is not None:
  302. self.handlers.update(handlers)
  303. def __call__(self, environ, start_response):
  304. path = environ['PATH_INFO']
  305. method = environ['REQUEST_METHOD']
  306. req = HTTPGitRequest(environ, start_response, dumb=self.dumb,
  307. handlers=self.handlers)
  308. # environ['QUERY_STRING'] has qs args
  309. handler = None
  310. for smethod, spath in self.services.keys():
  311. if smethod != method:
  312. continue
  313. mat = spath.search(path)
  314. if mat:
  315. handler = self.services[smethod, spath]
  316. break
  317. if handler is None:
  318. if self.fallback_app is not None:
  319. return self.fallback_app(environ, start_response)
  320. else:
  321. return [req.not_found('Sorry, that method is not supported')]
  322. return handler(req, self.backend, mat)
  323. class GunzipFilter(object):
  324. """WSGI middleware that unzips gzip-encoded requests before
  325. passing on to the underlying application.
  326. """
  327. def __init__(self, application):
  328. self.app = application
  329. def __call__(self, environ, start_response):
  330. if environ.get('HTTP_CONTENT_ENCODING', '') == 'gzip':
  331. try:
  332. environ['wsgi.input'].tell()
  333. wsgi_input = environ['wsgi.input']
  334. except (AttributeError, IOError, NotImplementedError):
  335. # The gzip implementation in the standard library of Python 2.x
  336. # requires working '.seek()' and '.tell()' methods on the input
  337. # stream. Read the data into a temporary file to work around
  338. # this limitation.
  339. wsgi_input = tempfile.SpooledTemporaryFile(16 * 1024 * 1024)
  340. shutil.copyfileobj(environ['wsgi.input'], wsgi_input)
  341. wsgi_input.seek(0)
  342. environ['wsgi.input'] = gzip.GzipFile(
  343. filename=None, fileobj=wsgi_input, mode='r')
  344. del environ['HTTP_CONTENT_ENCODING']
  345. if 'CONTENT_LENGTH' in environ:
  346. del environ['CONTENT_LENGTH']
  347. return self.app(environ, start_response)
  348. class LimitedInputFilter(object):
  349. """WSGI middleware that limits the input length of a request to that
  350. specified in Content-Length.
  351. """
  352. def __init__(self, application):
  353. self.app = application
  354. def __call__(self, environ, start_response):
  355. # This is not necessary if this app is run from a conforming WSGI
  356. # server. Unfortunately, there's no way to tell that at this point.
  357. # TODO: git may used HTTP/1.1 chunked encoding instead of specifying
  358. # content-length
  359. content_length = environ.get('CONTENT_LENGTH', '')
  360. if content_length:
  361. environ['wsgi.input'] = _LengthLimitedFile(
  362. environ['wsgi.input'], int(content_length))
  363. return self.app(environ, start_response)
  364. def make_wsgi_chain(*args, **kwargs):
  365. """Factory function to create an instance of HTTPGitApplication,
  366. correctly wrapped with needed middleware.
  367. """
  368. app = HTTPGitApplication(*args, **kwargs)
  369. wrapped_app = LimitedInputFilter(GunzipFilter(app))
  370. return wrapped_app
  371. class ServerHandlerLogger(ServerHandler):
  372. """ServerHandler that uses dulwich's logger for logging exceptions."""
  373. def log_exception(self, exc_info):
  374. logger.exception('Exception happened during processing of request',
  375. exc_info=exc_info)
  376. def log_message(self, format, *args):
  377. logger.info(format, *args)
  378. def log_error(self, *args):
  379. logger.error(*args)
  380. class WSGIRequestHandlerLogger(WSGIRequestHandler):
  381. """WSGIRequestHandler that uses dulwich's logger for logging exceptions."""
  382. def log_exception(self, exc_info):
  383. logger.exception('Exception happened during processing of request',
  384. exc_info=exc_info)
  385. def log_message(self, format, *args):
  386. logger.info(format, *args)
  387. def log_error(self, *args):
  388. logger.error(*args)
  389. def handle(self):
  390. """Handle a single HTTP request"""
  391. self.raw_requestline = self.rfile.readline()
  392. if not self.parse_request(): # An error code has been sent, just exit
  393. return
  394. handler = ServerHandlerLogger(
  395. self.rfile, self.wfile, self.get_stderr(), self.get_environ()
  396. )
  397. handler.request_handler = self # backpointer for logging
  398. handler.run(self.server.get_app())
  399. class WSGIServerLogger(WSGIServer):
  400. def handle_error(self, request, client_address):
  401. """Handle an error. """
  402. logger.exception(
  403. 'Exception happened during processing of request from %s' %
  404. str(client_address))
  405. def main(argv=sys.argv):
  406. """Entry point for starting an HTTP git server."""
  407. import optparse
  408. parser = optparse.OptionParser()
  409. parser.add_option("-l", "--listen_address", dest="listen_address",
  410. default="localhost",
  411. help="Binding IP address.")
  412. parser.add_option("-p", "--port", dest="port", type=int,
  413. default=8000,
  414. help="Port to listen on.")
  415. options, args = parser.parse_args(argv)
  416. if len(args) > 1:
  417. gitdir = args[1]
  418. else:
  419. gitdir = os.getcwd()
  420. log_utils.default_logging_config()
  421. backend = DictBackend({'/': Repo(gitdir)})
  422. app = make_wsgi_chain(backend)
  423. server = make_server(options.listen_address, options.port, app,
  424. handler_class=WSGIRequestHandlerLogger,
  425. server_class=WSGIServerLogger)
  426. logger.info('Listening for HTTP connections on %s:%d',
  427. options.listen_address, options.port)
  428. server.serve_forever()
  429. if __name__ == '__main__':
  430. main()