2
0

web.py 19 KB

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