web.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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 = [
  68. None,
  69. "Jan",
  70. "Feb",
  71. "Mar",
  72. "Apr",
  73. "May",
  74. "Jun",
  75. "Jul",
  76. "Aug",
  77. "Sep",
  78. "Oct",
  79. "Nov",
  80. "Dec",
  81. ]
  82. if timestamp is None:
  83. timestamp = time.time()
  84. year, month, day, hh, mm, ss, wd = time.gmtime(timestamp)[:7]
  85. return "%s, %02d %3s %4d %02d:%02d:%02d GMD" % (
  86. weekdays[wd],
  87. day,
  88. months[month],
  89. year,
  90. hh,
  91. mm,
  92. ss,
  93. )
  94. def url_prefix(mat) -> str:
  95. """Extract the URL prefix from a regex match.
  96. Args:
  97. mat: A regex match object.
  98. Returns: The URL prefix, defined as the text before the match in the
  99. original string. Normalized to start with one leading slash and end
  100. with zero.
  101. """
  102. return "/" + mat.string[: mat.start()].strip("/")
  103. def get_repo(backend, mat) -> BaseRepo:
  104. """Get a Repo instance for the given backend and URL regex match."""
  105. return backend.open_repository(url_prefix(mat))
  106. def send_file(req, f, content_type):
  107. """Send a file-like object to the request output.
  108. Args:
  109. req: The HTTPGitRequest object to send output to.
  110. f: An open file-like object to send; will be closed.
  111. content_type: The MIME type for the file.
  112. Returns: Iterator over the contents of the file, as chunks.
  113. """
  114. if f is None:
  115. yield req.not_found("File not found")
  116. return
  117. try:
  118. req.respond(HTTP_OK, content_type)
  119. while True:
  120. data = f.read(10240)
  121. if not data:
  122. break
  123. yield data
  124. except IOError:
  125. yield req.error("Error reading file")
  126. finally:
  127. f.close()
  128. def _url_to_path(url):
  129. return url.replace("/", os.path.sep)
  130. def get_text_file(req, backend, mat):
  131. req.nocache()
  132. path = _url_to_path(mat.group())
  133. logger.info("Sending plain text file %s", path)
  134. return send_file(req, get_repo(backend, mat).get_named_file(path), "text/plain")
  135. def get_loose_object(req, backend, mat):
  136. sha = (mat.group(1) + mat.group(2)).encode("ascii")
  137. logger.info("Sending loose object %s", sha)
  138. object_store = get_repo(backend, mat).object_store
  139. if not object_store.contains_loose(sha):
  140. yield req.not_found("Object not found")
  141. return
  142. try:
  143. data = object_store[sha].as_legacy_object()
  144. except IOError:
  145. yield req.error("Error reading object")
  146. return
  147. req.cache_forever()
  148. req.respond(HTTP_OK, "application/x-git-loose-object")
  149. yield data
  150. def get_pack_file(req, backend, mat):
  151. req.cache_forever()
  152. path = _url_to_path(mat.group())
  153. logger.info("Sending pack file %s", path)
  154. return send_file(
  155. req,
  156. get_repo(backend, mat).get_named_file(path),
  157. "application/x-git-packed-objects",
  158. )
  159. def get_idx_file(req, backend, mat):
  160. req.cache_forever()
  161. path = _url_to_path(mat.group())
  162. logger.info("Sending pack file %s", path)
  163. return send_file(
  164. req,
  165. get_repo(backend, mat).get_named_file(path),
  166. "application/x-git-packed-objects-toc",
  167. )
  168. def get_info_refs(req, backend, mat):
  169. params = parse_qs(req.environ["QUERY_STRING"])
  170. service = params.get("service", [None])[0]
  171. try:
  172. repo = get_repo(backend, mat)
  173. except NotGitRepository as e:
  174. yield req.not_found(str(e))
  175. return
  176. if service and not req.dumb:
  177. handler_cls = req.handlers.get(service.encode("ascii"), None)
  178. if handler_cls is None:
  179. yield req.forbidden("Unsupported service")
  180. return
  181. req.nocache()
  182. write = req.respond(HTTP_OK, "application/x-%s-advertisement" % service)
  183. proto = ReceivableProtocol(BytesIO().read, write)
  184. handler = handler_cls(
  185. backend,
  186. [url_prefix(mat)],
  187. proto,
  188. stateless_rpc=req,
  189. advertise_refs=True,
  190. )
  191. handler.proto.write_pkt_line(b"# service=" + service.encode("ascii") + b"\n")
  192. handler.proto.write_pkt_line(None)
  193. handler.handle()
  194. else:
  195. # non-smart fallback
  196. # TODO: select_getanyfile() (see http-backend.c)
  197. req.nocache()
  198. req.respond(HTTP_OK, "text/plain")
  199. logger.info("Emulating dumb info/refs")
  200. for text in generate_info_refs(repo):
  201. yield text
  202. def get_info_packs(req, backend, mat):
  203. req.nocache()
  204. req.respond(HTTP_OK, "text/plain")
  205. logger.info("Emulating dumb info/packs")
  206. return generate_objects_info_packs(get_repo(backend, mat))
  207. class _LengthLimitedFile(object):
  208. """Wrapper class to limit the length of reads from a file-like object.
  209. This is used to ensure EOF is read from the wsgi.input object once
  210. Content-Length bytes are read. This behavior is required by the WSGI spec
  211. but not implemented in wsgiref as of 2.5.
  212. """
  213. def __init__(self, input, max_bytes):
  214. self._input = input
  215. self._bytes_avail = max_bytes
  216. def read(self, size=-1):
  217. if self._bytes_avail <= 0:
  218. return b""
  219. if size == -1 or size > self._bytes_avail:
  220. size = self._bytes_avail
  221. self._bytes_avail -= size
  222. return self._input.read(size)
  223. # TODO: support more methods as necessary
  224. def handle_service_request(req, backend, mat):
  225. service = mat.group().lstrip("/")
  226. logger.info("Handling service request for %s", service)
  227. handler_cls = req.handlers.get(service.encode("ascii"), None)
  228. if handler_cls is None:
  229. yield req.forbidden("Unsupported service")
  230. return
  231. try:
  232. get_repo(backend, mat)
  233. except NotGitRepository as e:
  234. yield req.not_found(str(e))
  235. return
  236. req.nocache()
  237. write = req.respond(HTTP_OK, "application/x-%s-result" % service)
  238. proto = ReceivableProtocol(req.environ["wsgi.input"].read, write)
  239. # TODO(jelmer): Find a way to pass in repo, rather than having handler_cls
  240. # reopen.
  241. handler = handler_cls(backend, [url_prefix(mat)], proto, stateless_rpc=req)
  242. handler.handle()
  243. class HTTPGitRequest(object):
  244. """Class encapsulating the state of a single git HTTP request.
  245. :ivar environ: the WSGI environment for the request.
  246. """
  247. def __init__(self, environ, start_response, dumb: bool = False, handlers=None):
  248. self.environ = environ
  249. self.dumb = dumb
  250. self.handlers = handlers
  251. self._start_response = start_response
  252. self._cache_headers = [] # type: List[Tuple[str, str]]
  253. self._headers = [] # type: List[Tuple[str, str]]
  254. def add_header(self, name, value):
  255. """Add a header to the response."""
  256. self._headers.append((name, value))
  257. def respond(
  258. self,
  259. status: str = HTTP_OK,
  260. content_type: Optional[str] = None,
  261. headers: Optional[List[Tuple[str, str]]] = None,
  262. ):
  263. """Begin a response with the given status and other headers."""
  264. if headers:
  265. self._headers.extend(headers)
  266. if content_type:
  267. self._headers.append(("Content-Type", content_type))
  268. self._headers.extend(self._cache_headers)
  269. return self._start_response(status, self._headers)
  270. def not_found(self, message: str) -> bytes:
  271. """Begin a HTTP 404 response and return the text of a message."""
  272. self._cache_headers = []
  273. logger.info("Not found: %s", message)
  274. self.respond(HTTP_NOT_FOUND, "text/plain")
  275. return message.encode("ascii")
  276. def forbidden(self, message: str) -> bytes:
  277. """Begin a HTTP 403 response and return the text of a message."""
  278. self._cache_headers = []
  279. logger.info("Forbidden: %s", message)
  280. self.respond(HTTP_FORBIDDEN, "text/plain")
  281. return message.encode("ascii")
  282. def error(self, message: str) -> bytes:
  283. """Begin a HTTP 500 response and return the text of a message."""
  284. self._cache_headers = []
  285. logger.error("Error: %s", message)
  286. self.respond(HTTP_ERROR, "text/plain")
  287. return message.encode("ascii")
  288. def nocache(self) -> None:
  289. """Set the response to never be cached by the client."""
  290. self._cache_headers = [
  291. ("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"),
  292. ("Pragma", "no-cache"),
  293. ("Cache-Control", "no-cache, max-age=0, must-revalidate"),
  294. ]
  295. def cache_forever(self) -> None:
  296. """Set the response to be cached forever by the client."""
  297. now = time.time()
  298. self._cache_headers = [
  299. ("Date", date_time_string(now)),
  300. ("Expires", date_time_string(now + 31536000)),
  301. ("Cache-Control", "public, max-age=31536000"),
  302. ]
  303. class HTTPGitApplication(object):
  304. """Class encapsulating the state of a git WSGI application.
  305. :ivar backend: the Backend object backing this application
  306. """
  307. services = {
  308. ("GET", re.compile("/HEAD$")): get_text_file,
  309. ("GET", re.compile("/info/refs$")): get_info_refs,
  310. ("GET", re.compile("/objects/info/alternates$")): get_text_file,
  311. ("GET", re.compile("/objects/info/http-alternates$")): get_text_file,
  312. ("GET", re.compile("/objects/info/packs$")): get_info_packs,
  313. (
  314. "GET",
  315. re.compile("/objects/([0-9a-f]{2})/([0-9a-f]{38})$"),
  316. ): get_loose_object,
  317. (
  318. "GET",
  319. re.compile("/objects/pack/pack-([0-9a-f]{40})\\.pack$"),
  320. ): get_pack_file,
  321. (
  322. "GET",
  323. re.compile("/objects/pack/pack-([0-9a-f]{40})\\.idx$"),
  324. ): get_idx_file,
  325. ("POST", re.compile("/git-upload-pack$")): handle_service_request,
  326. ("POST", re.compile("/git-receive-pack$")): handle_service_request,
  327. }
  328. def __init__(self, backend, dumb: bool = False, handlers=None, fallback_app=None):
  329. self.backend = backend
  330. self.dumb = dumb
  331. self.handlers = dict(DEFAULT_HANDLERS)
  332. self.fallback_app = fallback_app
  333. if handlers is not None:
  334. self.handlers.update(handlers)
  335. def __call__(self, environ, start_response):
  336. path = environ["PATH_INFO"]
  337. method = environ["REQUEST_METHOD"]
  338. req = HTTPGitRequest(
  339. environ, start_response, dumb=self.dumb, handlers=self.handlers
  340. )
  341. # environ['QUERY_STRING'] has qs args
  342. handler = None
  343. for smethod, spath in self.services.keys():
  344. if smethod != method:
  345. continue
  346. mat = spath.search(path)
  347. if mat:
  348. handler = self.services[smethod, spath]
  349. break
  350. if handler is None:
  351. if self.fallback_app is not None:
  352. return self.fallback_app(environ, start_response)
  353. else:
  354. return [req.not_found("Sorry, that method is not supported")]
  355. return handler(req, self.backend, mat)
  356. class GunzipFilter(object):
  357. """WSGI middleware that unzips gzip-encoded requests before
  358. passing on to the underlying application.
  359. """
  360. def __init__(self, application):
  361. self.app = application
  362. def __call__(self, environ, start_response):
  363. if environ.get("HTTP_CONTENT_ENCODING", "") == "gzip":
  364. try:
  365. environ["wsgi.input"].tell()
  366. wsgi_input = environ["wsgi.input"]
  367. except (AttributeError, IOError, NotImplementedError):
  368. # The gzip implementation in the standard library of Python 2.x
  369. # requires working '.seek()' and '.tell()' methods on the input
  370. # stream. Read the data into a temporary file to work around
  371. # this limitation.
  372. wsgi_input = tempfile.SpooledTemporaryFile(16 * 1024 * 1024)
  373. shutil.copyfileobj(environ["wsgi.input"], wsgi_input)
  374. wsgi_input.seek(0)
  375. environ["wsgi.input"] = gzip.GzipFile(
  376. filename=None, fileobj=wsgi_input, mode="r"
  377. )
  378. del environ["HTTP_CONTENT_ENCODING"]
  379. if "CONTENT_LENGTH" in environ:
  380. del environ["CONTENT_LENGTH"]
  381. return self.app(environ, start_response)
  382. class LimitedInputFilter(object):
  383. """WSGI middleware that limits the input length of a request to that
  384. specified in Content-Length.
  385. """
  386. def __init__(self, application):
  387. self.app = application
  388. def __call__(self, environ, start_response):
  389. # This is not necessary if this app is run from a conforming WSGI
  390. # server. Unfortunately, there's no way to tell that at this point.
  391. # TODO: git may used HTTP/1.1 chunked encoding instead of specifying
  392. # content-length
  393. content_length = environ.get("CONTENT_LENGTH", "")
  394. if content_length:
  395. environ["wsgi.input"] = _LengthLimitedFile(
  396. environ["wsgi.input"], int(content_length)
  397. )
  398. return self.app(environ, start_response)
  399. def make_wsgi_chain(*args, **kwargs):
  400. """Factory function to create an instance of HTTPGitApplication,
  401. correctly wrapped with needed middleware.
  402. """
  403. app = HTTPGitApplication(*args, **kwargs)
  404. wrapped_app = LimitedInputFilter(GunzipFilter(app))
  405. return wrapped_app
  406. class ServerHandlerLogger(ServerHandler):
  407. """ServerHandler that uses dulwich's logger for logging exceptions."""
  408. def log_exception(self, exc_info):
  409. logger.exception(
  410. "Exception happened during processing of request",
  411. exc_info=exc_info,
  412. )
  413. def log_message(self, format, *args):
  414. logger.info(format, *args)
  415. def log_error(self, *args):
  416. logger.error(*args)
  417. class WSGIRequestHandlerLogger(WSGIRequestHandler):
  418. """WSGIRequestHandler that uses dulwich's logger for logging exceptions."""
  419. def log_exception(self, exc_info):
  420. logger.exception(
  421. "Exception happened during processing of request",
  422. exc_info=exc_info,
  423. )
  424. def log_message(self, format, *args):
  425. logger.info(format, *args)
  426. def log_error(self, *args):
  427. logger.error(*args)
  428. def handle(self):
  429. """Handle a single HTTP request"""
  430. self.raw_requestline = self.rfile.readline()
  431. if not self.parse_request(): # An error code has been sent, just exit
  432. return
  433. handler = ServerHandlerLogger(
  434. self.rfile, self.wfile, self.get_stderr(), self.get_environ()
  435. )
  436. handler.request_handler = self # backpointer for logging
  437. handler.run(self.server.get_app())
  438. class WSGIServerLogger(WSGIServer):
  439. def handle_error(self, request, client_address):
  440. """Handle an error. """
  441. logger.exception(
  442. "Exception happened during processing of request from %s"
  443. % str(client_address)
  444. )
  445. def main(argv=sys.argv):
  446. """Entry point for starting an HTTP git server."""
  447. import optparse
  448. parser = optparse.OptionParser()
  449. parser.add_option(
  450. "-l",
  451. "--listen_address",
  452. dest="listen_address",
  453. default="localhost",
  454. help="Binding IP address.",
  455. )
  456. parser.add_option(
  457. "-p",
  458. "--port",
  459. dest="port",
  460. type=int,
  461. default=8000,
  462. help="Port to listen on.",
  463. )
  464. options, args = parser.parse_args(argv)
  465. if len(args) > 1:
  466. gitdir = args[1]
  467. else:
  468. gitdir = os.getcwd()
  469. log_utils.default_logging_config()
  470. backend = DictBackend({"/": Repo(gitdir)})
  471. app = make_wsgi_chain(backend)
  472. server = make_server(
  473. options.listen_address,
  474. options.port,
  475. app,
  476. handler_class=WSGIRequestHandlerLogger,
  477. server_class=WSGIServerLogger,
  478. )
  479. logger.info(
  480. "Listening for HTTP connections on %s:%d",
  481. options.listen_address,
  482. options.port,
  483. )
  484. server.serve_forever()
  485. if __name__ == "__main__":
  486. main()