web.py 18 KB

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