web.py 18 KB

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