web.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. def _chunk_iter(f):
  208. while True:
  209. line = f.readline()
  210. length = int(line.rstrip(), 16)
  211. chunk = f.read(length + 2)
  212. if length == 0:
  213. break
  214. yield chunk[:-2]
  215. class ChunkReader(object):
  216. def __init__(self, f):
  217. self._iter = _chunk_iter(f)
  218. self._buffer = []
  219. def read(self, n):
  220. while sum(map(len, self._buffer)) < n:
  221. try:
  222. self._buffer.append(next(self._iter))
  223. except StopIteration:
  224. break
  225. f = b''.join(self._buffer)
  226. ret = f[:n]
  227. self._buffer = [f[n:]]
  228. return ret
  229. class _LengthLimitedFile(object):
  230. """Wrapper class to limit the length of reads from a file-like object.
  231. This is used to ensure EOF is read from the wsgi.input object once
  232. Content-Length bytes are read. This behavior is required by the WSGI spec
  233. but not implemented in wsgiref as of 2.5.
  234. """
  235. def __init__(self, input, max_bytes):
  236. self._input = input
  237. self._bytes_avail = max_bytes
  238. def read(self, size=-1):
  239. if self._bytes_avail <= 0:
  240. return b""
  241. if size == -1 or size > self._bytes_avail:
  242. size = self._bytes_avail
  243. self._bytes_avail -= size
  244. return self._input.read(size)
  245. # TODO: support more methods as necessary
  246. def handle_service_request(req, backend, mat):
  247. service = mat.group().lstrip("/")
  248. logger.info("Handling service request for %s", service)
  249. handler_cls = req.handlers.get(service.encode("ascii"), None)
  250. if handler_cls is None:
  251. yield req.forbidden("Unsupported service")
  252. return
  253. try:
  254. get_repo(backend, mat)
  255. except NotGitRepository as e:
  256. yield req.not_found(str(e))
  257. return
  258. req.nocache()
  259. write = req.respond(HTTP_OK, "application/x-%s-result" % service)
  260. if req.environ.get('HTTP_TRANSFER_ENCODING') == 'chunked':
  261. read = ChunkReader(req.environ["wsgi.input"]).read
  262. else:
  263. read = req.environ["wsgi.input"].read
  264. proto = ReceivableProtocol(read, write)
  265. # TODO(jelmer): Find a way to pass in repo, rather than having handler_cls
  266. # reopen.
  267. handler = handler_cls(backend, [url_prefix(mat)], proto, stateless_rpc=req)
  268. handler.handle()
  269. class HTTPGitRequest(object):
  270. """Class encapsulating the state of a single git HTTP request.
  271. Attributes:
  272. environ: the WSGI environment for the request.
  273. """
  274. def __init__(self, environ, start_response, dumb: bool = False, handlers=None):
  275. self.environ = environ
  276. self.dumb = dumb
  277. self.handlers = handlers
  278. self._start_response = start_response
  279. self._cache_headers = [] # type: List[Tuple[str, str]]
  280. self._headers = [] # type: List[Tuple[str, str]]
  281. def add_header(self, name, value):
  282. """Add a header to the response."""
  283. self._headers.append((name, value))
  284. def respond(
  285. self,
  286. status: str = HTTP_OK,
  287. content_type: Optional[str] = None,
  288. headers: Optional[List[Tuple[str, str]]] = None,
  289. ):
  290. """Begin a response with the given status and other headers."""
  291. if headers:
  292. self._headers.extend(headers)
  293. if content_type:
  294. self._headers.append(("Content-Type", content_type))
  295. self._headers.extend(self._cache_headers)
  296. return self._start_response(status, self._headers)
  297. def not_found(self, message: str) -> bytes:
  298. """Begin a HTTP 404 response and return the text of a message."""
  299. self._cache_headers = []
  300. logger.info("Not found: %s", message)
  301. self.respond(HTTP_NOT_FOUND, "text/plain")
  302. return message.encode("ascii")
  303. def forbidden(self, message: str) -> bytes:
  304. """Begin a HTTP 403 response and return the text of a message."""
  305. self._cache_headers = []
  306. logger.info("Forbidden: %s", message)
  307. self.respond(HTTP_FORBIDDEN, "text/plain")
  308. return message.encode("ascii")
  309. def error(self, message: str) -> bytes:
  310. """Begin a HTTP 500 response and return the text of a message."""
  311. self._cache_headers = []
  312. logger.error("Error: %s", message)
  313. self.respond(HTTP_ERROR, "text/plain")
  314. return message.encode("ascii")
  315. def nocache(self) -> None:
  316. """Set the response to never be cached by the client."""
  317. self._cache_headers = [
  318. ("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"),
  319. ("Pragma", "no-cache"),
  320. ("Cache-Control", "no-cache, max-age=0, must-revalidate"),
  321. ]
  322. def cache_forever(self) -> None:
  323. """Set the response to be cached forever by the client."""
  324. now = time.time()
  325. self._cache_headers = [
  326. ("Date", date_time_string(now)),
  327. ("Expires", date_time_string(now + 31536000)),
  328. ("Cache-Control", "public, max-age=31536000"),
  329. ]
  330. class HTTPGitApplication(object):
  331. """Class encapsulating the state of a git WSGI application.
  332. Attributes:
  333. backend: the Backend object backing this application
  334. """
  335. services = {
  336. ("GET", re.compile("/HEAD$")): get_text_file,
  337. ("GET", re.compile("/info/refs$")): get_info_refs,
  338. ("GET", re.compile("/objects/info/alternates$")): get_text_file,
  339. ("GET", re.compile("/objects/info/http-alternates$")): get_text_file,
  340. ("GET", re.compile("/objects/info/packs$")): get_info_packs,
  341. (
  342. "GET",
  343. re.compile("/objects/([0-9a-f]{2})/([0-9a-f]{38})$"),
  344. ): get_loose_object,
  345. (
  346. "GET",
  347. re.compile("/objects/pack/pack-([0-9a-f]{40})\\.pack$"),
  348. ): get_pack_file,
  349. (
  350. "GET",
  351. re.compile("/objects/pack/pack-([0-9a-f]{40})\\.idx$"),
  352. ): get_idx_file,
  353. ("POST", re.compile("/git-upload-pack$")): handle_service_request,
  354. ("POST", re.compile("/git-receive-pack$")): handle_service_request,
  355. }
  356. def __init__(self, backend, dumb: bool = False, handlers=None, fallback_app=None):
  357. self.backend = backend
  358. self.dumb = dumb
  359. self.handlers = dict(DEFAULT_HANDLERS)
  360. self.fallback_app = fallback_app
  361. if handlers is not None:
  362. self.handlers.update(handlers)
  363. def __call__(self, environ, start_response):
  364. path = environ["PATH_INFO"]
  365. method = environ["REQUEST_METHOD"]
  366. req = HTTPGitRequest(
  367. environ, start_response, dumb=self.dumb, handlers=self.handlers
  368. )
  369. # environ['QUERY_STRING'] has qs args
  370. handler = None
  371. for smethod, spath in self.services.keys():
  372. if smethod != method:
  373. continue
  374. mat = spath.search(path)
  375. if mat:
  376. handler = self.services[smethod, spath]
  377. break
  378. if handler is None:
  379. if self.fallback_app is not None:
  380. return self.fallback_app(environ, start_response)
  381. else:
  382. return [req.not_found("Sorry, that method is not supported")]
  383. return handler(req, self.backend, mat)
  384. class GunzipFilter(object):
  385. """WSGI middleware that unzips gzip-encoded requests before
  386. passing on to the underlying application.
  387. """
  388. def __init__(self, application):
  389. self.app = application
  390. def __call__(self, environ, start_response):
  391. if environ.get("HTTP_CONTENT_ENCODING", "") == "gzip":
  392. try:
  393. environ["wsgi.input"].tell()
  394. wsgi_input = environ["wsgi.input"]
  395. except (AttributeError, IOError, NotImplementedError):
  396. # The gzip implementation in the standard library of Python 2.x
  397. # requires working '.seek()' and '.tell()' methods on the input
  398. # stream. Read the data into a temporary file to work around
  399. # this limitation.
  400. wsgi_input = tempfile.SpooledTemporaryFile(16 * 1024 * 1024)
  401. shutil.copyfileobj(environ["wsgi.input"], wsgi_input)
  402. wsgi_input.seek(0)
  403. environ["wsgi.input"] = gzip.GzipFile(
  404. filename=None, fileobj=wsgi_input, mode="r"
  405. )
  406. del environ["HTTP_CONTENT_ENCODING"]
  407. if "CONTENT_LENGTH" in environ:
  408. del environ["CONTENT_LENGTH"]
  409. return self.app(environ, start_response)
  410. class LimitedInputFilter(object):
  411. """WSGI middleware that limits the input length of a request to that
  412. specified in Content-Length.
  413. """
  414. def __init__(self, application):
  415. self.app = application
  416. def __call__(self, environ, start_response):
  417. # This is not necessary if this app is run from a conforming WSGI
  418. # server. Unfortunately, there's no way to tell that at this point.
  419. # TODO: git may used HTTP/1.1 chunked encoding instead of specifying
  420. # content-length
  421. content_length = environ.get("CONTENT_LENGTH", "")
  422. if content_length:
  423. environ["wsgi.input"] = _LengthLimitedFile(
  424. environ["wsgi.input"], int(content_length)
  425. )
  426. return self.app(environ, start_response)
  427. def make_wsgi_chain(*args, **kwargs):
  428. """Factory function to create an instance of HTTPGitApplication,
  429. correctly wrapped with needed middleware.
  430. """
  431. app = HTTPGitApplication(*args, **kwargs)
  432. wrapped_app = LimitedInputFilter(GunzipFilter(app))
  433. return wrapped_app
  434. class ServerHandlerLogger(ServerHandler):
  435. """ServerHandler that uses dulwich's logger for logging exceptions."""
  436. def log_exception(self, exc_info):
  437. logger.exception(
  438. "Exception happened during processing of request",
  439. exc_info=exc_info,
  440. )
  441. def log_message(self, format, *args):
  442. logger.info(format, *args)
  443. def log_error(self, *args):
  444. logger.error(*args)
  445. class WSGIRequestHandlerLogger(WSGIRequestHandler):
  446. """WSGIRequestHandler that uses dulwich's logger for logging exceptions."""
  447. def log_exception(self, exc_info):
  448. logger.exception(
  449. "Exception happened during processing of request",
  450. exc_info=exc_info,
  451. )
  452. def log_message(self, format, *args):
  453. logger.info(format, *args)
  454. def log_error(self, *args):
  455. logger.error(*args)
  456. def handle(self):
  457. """Handle a single HTTP request"""
  458. self.raw_requestline = self.rfile.readline()
  459. if not self.parse_request(): # An error code has been sent, just exit
  460. return
  461. handler = ServerHandlerLogger(
  462. self.rfile, self.wfile, self.get_stderr(), self.get_environ()
  463. )
  464. handler.request_handler = self # backpointer for logging
  465. handler.run(self.server.get_app())
  466. class WSGIServerLogger(WSGIServer):
  467. def handle_error(self, request, client_address):
  468. """Handle an error. """
  469. logger.exception(
  470. "Exception happened during processing of request from %s"
  471. % str(client_address)
  472. )
  473. def main(argv=sys.argv):
  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()