web.py 19 KB

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